如果 C# 结构只有只读属性
Should a C# struct have only read-only properties
我在 Whosebug here 上阅读了一个关于不纯方法的问题,它让我开始思考结构设计的最佳实践。
阅读有关创建不可变结构的示例here 属性仅定义为吸气剂。
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public bool HasValue { get { return hasValue; } }
其他地方的其他示例,包括 System.Drawing.Point
中的属性具有 getter 和 setter。
public int Y {
get {
return y;
}
set {
y = value;
}
}
design guidelines 没有具体说明,但非常简洁。对于结构属性,推荐的方法是什么?只读还是允许写入?
设计指南对此非常明确:
X DO NOT define mutable value types.
Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.
至于 System.Drawing.Point
,还有其他重要因素(如性能)足以打破此设计准则。参见 Why are System.Drawing Rectangle, Point, Size etc mutable structs and not classes?
结构通常应尝试表现为不可变对象或表现为一堆用胶带粘在一起的变量(例如,点的坐标)。这是两种不相交的使用模式,MSDN 准则适用于第一种而不适用于第二种。
前一种结构的所有属性都应该是只读的;后一种结构应该通过 public 字段公开其所有状态,但可以完全合理地 也 提供 "convenience" 属性,这些属性是基于定义的方式计算的public 字段的内容。例如,Rectangle
可能具有字段 X
、Y
、Width
和 Height
,以及便利属性 Right
和 Bottom
.此类属性不会公开无法通过 public 字段直接访问的功能,但会允许更方便地实现某些使用模式。
我在 Whosebug here 上阅读了一个关于不纯方法的问题,它让我开始思考结构设计的最佳实践。
阅读有关创建不可变结构的示例here 属性仅定义为吸气剂。
public DateTime Start { get { return start; } }
public DateTime End { get { return end; } }
public bool HasValue { get { return hasValue; } }
其他地方的其他示例,包括 System.Drawing.Point
中的属性具有 getter 和 setter。
public int Y {
get {
return y;
}
set {
y = value;
}
}
design guidelines 没有具体说明,但非常简洁。对于结构属性,推荐的方法是什么?只读还是允许写入?
设计指南对此非常明确:
X DO NOT define mutable value types.
Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.
至于 System.Drawing.Point
,还有其他重要因素(如性能)足以打破此设计准则。参见 Why are System.Drawing Rectangle, Point, Size etc mutable structs and not classes?
结构通常应尝试表现为不可变对象或表现为一堆用胶带粘在一起的变量(例如,点的坐标)。这是两种不相交的使用模式,MSDN 准则适用于第一种而不适用于第二种。
前一种结构的所有属性都应该是只读的;后一种结构应该通过 public 字段公开其所有状态,但可以完全合理地 也 提供 "convenience" 属性,这些属性是基于定义的方式计算的public 字段的内容。例如,Rectangle
可能具有字段 X
、Y
、Width
和 Height
,以及便利属性 Right
和 Bottom
.此类属性不会公开无法通过 public 字段直接访问的功能,但会允许更方便地实现某些使用模式。