在阅读了很多关于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
}
Run Code Online (Sandbox Code Playgroud)
我认为编译器的工作非常简单,因为它需要检查一些事情:
这个设计让我想到了一些可能的问题:
IEnumerable<T>)不变性取决于类型的不变性<T>.建议的immutable关键字在此上下文中没有用,因为您无法声明它IEnumerable<string>是不可变的,即使它是.之前说明的原因是否足以使此关键字不存在?我错过了任何其他缺点吗?对于这种语言的大变化,这是不是必要的吗?
简短的版本是:因为没有人提出、规范、设计、实现、测试、记录、翻译和支持该功能。
较长的版本将涉及为什么要这样做,因为它可以通过readonly现场间接实现 -它会增加什么好处。
对于课程来说,事实证明它相对较小。请注意,有一个[ImmutableObject(true)]属性可以使用,但没有任何功能或框架真正有用它,所以......没有人使用它。
有人提议在 C# 的未来版本中添加“只读结构”(与ref局部变量相关,Span<T>等等)——但是:它死了并消失了。然而,这些ref readonly东西仍然存在,这是为了防止实例方法的重新this分配struct。