[英]Immutable vs Mutable C#
我正在尝试编写一个快速片段来演示不可变类型和可变类型之间的区别。 这段代码对你们所有人来说似乎都是正确的吗?
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!");
}
}
是的,这看起来很合理。
但是,我也会谈论“泄漏”的可变性。 例如:
public class AppearsImmutableButIsntDeeplyImmutable
{
private readonly StringBuilder builder = new StringBuilder();
public StringBuilder Builder { get { return builder; } }
}
我无法更改实例出现在哪个构建器上,但我可以这样做:
value.Builder.Append("hello");
值得您阅读 Eric Lippert 关于各种不变性的博客文章 - 以及该系列文章中的所有 rest。
是的,看起来没错。
请注意,私有成员不需要是只读的,class 是不可变的,这只是针对 class 内部代码损坏的额外预防措施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.