【发布时间】:2011-09-27 23:52:02
【问题描述】:
我正在阅读 Eric Liperts 的关于 Mutating Readonly Structs 的博客,并且我在 SO 中看到许多对这个博客的引用,作为为什么值类型必须是不可变的论点。 但仍有一件事不清楚,说当您访问值类型时,您总是会得到它的副本,这是示例:
struct Mutable
{
private int x;
public int Mutate()
{
this.x = this.x + 1;
return this.x;
}
}
class Test
{
public readonly Mutable m = new Mutable();
static void Main(string[] args)
{
Test t = new Test();
System.Console.WriteLine(t.m.Mutate());
System.Console.WriteLine(t.m.Mutate());
System.Console.WriteLine(t.m.Mutate());
}
}
问题是为什么当我改变
public readonly Mutable m = new Mutable();
到
public Mutable m = new Mutable();
一切都开始工作了预期。
请您更清楚地解释为什么值类型必须是不可变的。 我知道这对线程安全有好处,但在这种情况下,同样可以应用于引用类型。
【问题讨论】:
-
如果不从您链接到的博客文章中复制和粘贴更多引用,我将不知道如何回答这个问题。
m是readonly是什么使t.m成为一个值,它不是一个变量,然后被放置在一个临时变量中,并且正是这个临时变量是this在Mutate方法中。去掉readonly,剩下的因素不再适用,所以Mutate内的this可以是m。