[英]Is it best practice for a C# property getter to return a new object?
I am often writing classes that create a new object in a property getter, but I have read this is not necessarily best practice. 我经常编写在属性getter中创建新对象的类,但我读过这不一定是最佳实践。 Eg: 例如:
public class Board
{
public float Width { get; }
public float Height { get; }
public CGSize Size { get { return new CGSize(this.Width, this.Height); } }
public Board(float width, float height)
{
this.Width = width;
this.Height = height;
}
}
Is there anything wrong with that? 那有什么不对吗?
See here: Is object creation in getters bad practice? 看到这里: 在getter中创建对象是不是很糟糕? where various upvoted people suggest it is bad practice, eg: "Yes, it is bad practice. Ideally, a getter should not be changing or creating anything". 各种受欢迎的人都认为这是不好的做法,例如:“是的,这是不好的做法。理想情况下,吸气剂不应该改变或创造任何东西”。 And that reading a property twice should produce identical results (whereas creating a new object will be different each time.) 并且两次读取属性应该产生相同的结果(而每次创建一个新对象会有所不同。)
(I note that in C# the System.Drawing.Rectangle class has a Size property that does return a new object each time.) (我注意到在C#中,System.Drawing.Rectangle类有一个Size属性,每次都返回一个新对象。)
Creating a new object is a good defensive strategy to prevent modifications of your object's internals. 创建新对象是一种很好的防御策略,可以防止修改对象的内部。
However, it should be applied only when the object that you are returning is a mutable, and is not a struct
(which should be immutable anyway [why?] ). 但是,它应该仅在您返回的对象是可变的时才应用,并且不是struct
(无论如何都应该是不可变的[为什么?] )。
CGSize
is a struct
, so you are creating a new value-typed object here. CGSize
是一个struct
,所以你在这里创建一个新的值类型对象。 This is exactly what you should do when you do not store the Size
. 这正是您不存储Size
时应该执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.