C# 中的不可变类型和不可变属性是什么意思?能举个简单的例子吗?
最佳答案
不可变类型是其属性只能在初始化时设置的类型。一旦创建了对象,就不能再进行任何更改。不可变属性只是一个只读属性。
在下面的示例中,ImmutableType
是一种具有一个属性 Test
的不可变类型。测试是一个只读属性。只能在构造时设置。
class ImmutableType
{
private readonly string _test;
public string Test
{
get { return _test; }
}
public ImmutableType(string test)
{
_test = test;
}
}
另见:The Wikipedia article , 和 some Stack Overflow questions关于这个话题。
关于c# - C# 中的不可变类型和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2537620/