我正在尝试编写一个快速代码片段来演示不可变类型和可变类型之间的区别.这段代码看起来对你们好吗?
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!");
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 14
是的,这看起来很合理.
但是,我也会谈到"漏洞"的可变性.例如:
public class AppearsImmutableButIsntDeeplyImmutable
{
private readonly StringBuilder builder = new StringBuilder();
public StringBuilder Builder { get { return builder; } }
}
Run Code Online (Sandbox Code Playgroud)
我无法改变它 Builder中实例出现,但我可以这样做:
value.Builder.Append("hello");
Run Code Online (Sandbox Code Playgroud)
值得你阅读Eric Lippert关于各种不变性的博客文章- 以及系列中其他所有帖子.