C# 属性 getter 到 return 新对象的最佳实践是什么?

Is it best practice for a C# property getter to return a new object?

我经常写 classes 在 属性 getter 中创建一个新对象,但我读到这不一定是最佳实践。例如:

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 object creation in getters bad practice? 各种赞成的人认为这是不好的做法,例如:"Yes, it is bad practice. Ideally, a getter should not be changing or creating anything"。并且读取 属性 两次应该会产生 相同的 结果(而每次创建新对象都会不同。)

(我注意到在 C# 中,System.Drawing.Rectangle class 的大小 属性 每次都会 return 一个新对象。)

创建新对象是一种很好的防御策略,可以防止修改对象的内部结构。

但是,只有当您返回的对象是可变的,而不是 struct(无论如何都应该是不可变的 [why?])时才应该应用它。

CGSize 是一个 struct,所以您在这里创建了一个新的值类型对象。当您不存储 Size.

时,这正是您应该做的