我正在尝试编写一个快速代码段来演示不可变类型和可变类型之间的区别。 这段代码对你们好吗?
class MutableTypeExample
{
private string _test; //members are not readonly
public string Test
{
get { return _test; }
set { _test = value; } //class is mutable because it can be modified after being created
}
public MutableTypeExample(string test)
{
_test = test;
}
public void MakeTestFoo()
{
this.Test = "FOO!";
}
}
class ImmutableTypeExample
{
private readonly string _test; //all members are readonly
public string Test
{
get { return _test; } //no set allowed
}
public ImmutableTypeExample(string test) //immutable means you can only set members in the consutrctor. Once the object is instantiated it cannot be altered
{
_test = test;
}
public ImmutableTypeExample MakeTestFoo()
{
//this.Test = "FOO!"; //not allowed because it is readonly
return new ImmutableTypeExample("FOO!");
}
}
答案 0 :(得分:14)
但是,我也谈论“漏洞”的可变性。例如:
public class AppearsImmutableButIsntDeeplyImmutable
{
private readonly StringBuilder builder = new StringBuilder();
public StringBuilder Builder { get { return builder; } }
}
我无法更改实例出现的构建器,但我可以这样做:
value.Builder.Append("hello");
值得你阅读Eric Lippert关于kinds of immutability的博客文章 - 以及系列中其他所有帖子。
答案 1 :(得分:4)
是的,看起来不错。
请注意,私有成员不需要只读取该类是不可变的,这只是一个额外的预防措施,再次破坏了类中的代码。