不可变与可变C#

Hoo*_*ody 5 c# oop

我正在尝试编写一个快速代码片段来演示不可变类型和可变类型之间的区别.这段代码看起来对你们好吗?

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关于各种不变性的博客文章- 以及系列中其他所有帖子.


Guf*_*ffa 5

是的,看起来是对的。

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