gpt4 book ai didi

c# - 不可变与可变 C#

转载 作者:太空狗 更新时间:2023-10-29 22:08:30 26 4
gpt4 key购买 nike

我正在尝试编写一个简短的片段来演示不可变类型和可变类型之间的区别。这段代码似乎适合你们吗?

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com