在阅读了很多关于C#的不变性并且理解它的好处(没有副作用,安全字典键,多线程......)后,我想到了一个问题:
为什么C#中没有关键字断言类(或结构)是不可变的?此关键字应在编译时检查您是否无法改变类(或结构)。例如:
public immutable class MyImmutableClass
{
public readonly string field;
public string field2; //This would be a compile time error
public readonly AnyMutableType field3; //This would be a compile time error
public string Prop { get; }
public string Prop2 { get; set; } //This would be a compile time error
public AnyMutableType Prop3 { get; } //This would be a compile time error
}
我认为编译器的工作非常简单,因为它需要检查一些事情:
这种设计让我想到了一些可能的问题:
IEnumerable<T>
)不变性将取决于类型<T>
的不变性。建议的immutable
关键字在此上下文中没有用,因为您无法声明IEnumerable<string>
是不可变的,即使它是。此关键字之前是否存在足够的原因? 我错过了任何其他缺点吗? 这对语言的这种重大变化来说还不够吗?
答案 0 :(得分:4)
简短版本将是:因为没有人提出,规范,设计,实施,测试,记录,翻译和支持该功能。
较长的版本与为什么有关,因为它可以通过readonly
字段间接实现 - 它会添加什么好处。
对于课程,结果是相对次要。请注意,可以使用[ImmutableObject(true)]
属性,但没有任何功能或框架真正有用,所以......没有人使用它。
是一个添加&#34; readonly structs&#34;在C#的未来版本中(与ref
本地人,Span<T>
等相关) - 但是:它死了并且消失了。但是,ref readonly
内容依然存在,这是为了防止在this
实例方法中重新分配struct
。