我正在尝试理解一些基本概念:
class Program
{
private static readonly MyStruct m = new MyStruct();
static void Main(string[] args)
{
//new MutableSample().RunSample();
Console.WriteLine(m.ChangeInternal());
Console.WriteLine(m.ChangeInternal());
Console.WriteLine(m.ChangeInternal());
Console.Read();
}
}
public struct MyStruct
{
private int x;
public int ChangeInternal()
{
this.x = this.x + 1;
return this.x;
}
}
当我运行这段代码时,它会给出 1、1、1,但是当我删除“只读”时,它会显示 1、2、3。
有人能给我解释一下吗?
最佳答案
C# 规范的第 7.5.4 节指出:
[...] if the field is readonly and the reference occurs outside an instance constructor of the class in which the field is declared, then the result is a value, namely the value of the field I in the object referenced by E
因此,当该字段为readonly
时,您正在改变一个副本(因为改变一个值是不可能的,只能改变一个变量)。如果不是,您正在改变字段本身。
这在 this blog post 中有更详细的描述。埃里克·利珀特着。引用它的结尾:
This is yet another reason why mutable value types are evil. Try to always make value types immutable.
关于c# - 只读更改结构的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26721550/