Looking into the .NET code,
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
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
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.
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.