¿Por qué Rectangle.Size crea nuevas instancias en cada llamada?

Looking into the .NET code, Rectangle.Size devoluciones new Size(Width, Height). Why did Microsoft choose this pattern? Personally, I would have thought that Size would be stored within the structure, and Rectangle.Width, for example, would return Size.Width. This would prevent a new structure from being created every property call. I'm guessing that there are some properties of immutability that influenced this decision, but I'm not sure what.

preguntado el 27 de agosto de 11 a las 19:08

Problem is, now every call to Width or Height generates a copy of the structure. This copy can't be suppressed, a lot of the classes that have a Rectangle derive from MarshalByRefObject which prevents properties from being inlined. Which property is used most often? Hard to say, but the Rectangle methods themselves never use Size. -

@Hans - Why does each call generate a new copy? Can't each Rectangle just have its own internal Size structure? -

Assume you have a Rectangle type with an internal Size field. Now think about how you implement the Width and Height property getters. -

2 Respuestas

Size is a struct, so it's not like it's creating a new object on the heap. It will create a new copy of a Size value whatever you do.

I can't see that it's going to make much difference either way, to be honest. Given that the Width y Height propiedades de Size are inlined, I can see that there wouldn't be much penalty from storing a Size as you suggest... but equally I can see that the constructor for Size is so trivial that the JIT may well be able to convert the Rectangle.Size property to almost exactly the same native code.

So I agree it's a ligeramente odd decision, but I don't think it's going to hurt anyone much. Perhaps it makes serialization simpler or something like that.

Respondido 27 ago 11, 23:08

If you always get a link to the actual size you would create side effects when changing them. If your intention is to change them, you have to use the properties or getters and setters of the object you want to manipulate. If you want to use them for something else (calculating layout etc) this is the most proper solution.

Respondido 29 ago 11, 12:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.