不可变c# vs可变c#

本文关键字:可变 vs 不可变 | 更新日期: 2023-09-27 18:05:49

我试图编写一个简短的代码片段来演示不可变类型和可变类型之间的区别。你们觉得这个代码对吗?

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!");
    }
}

不可变c# vs可变c#

是啊,看起来很合理。

然而,我也会谈论"泄漏"可变性。例如:

public class AppearsImmutableButIsntDeeplyImmutable
{
    private readonly StringBuilder builder = new StringBuilder();
    public StringBuilder Builder { get { return builder; } }
}

我不能改变实例出现在哪个生成器上,但是我可以这样做:

value.Builder.Append("hello");

值得一读Eric Lippert关于各种不变性的博文——以及本系列中所有其他的博文。

是的,看起来不错。

请注意,要使类不可变,private成员不需要是只读的,这只是防止类内部代码损坏的额外预防措施。