c# - 不可变与可变 C#

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

最佳答案

是的,这看起来很合理。

但是,我谈论“泄漏的”可变性。例如:

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

我无法更改实例出现在哪个构建器上,但我可以:

value.Builder.Append("hello");

Eric Lippert 在 kinds of immutability 上的博文值得您阅读- 实际上是该系列的所有其他帖子。

关于c# - 不可变与可变 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7078857/

相关文章:

c# - 简单的 try/catch 不使用任何异常

php - 将子类映射为其扩展父类

c++ - 如何实现应用程序事件记录器

C++ 设计 : Pool and pointers VS client-server

c++ - 为什么我不能在类中使用参数构造函数?

javascript - 为什么在外部源文件中声明时会加载对象文字,但在包含外部 javascript 文件的文件中调用时却不会加载

c# - 无法为此文件显示设计器,因为无法设计其中的任何类

c# - Fluent NHibernate,引用硬编码的 C# 方法

c# - 我如何在 C# 中显示每个循环到文本框?

c# - 在指定的时间间隔内在 C# 中创建一个随机 GUID