c# - 只读更改结构的行为

标签 c# immutability readonly

我正在尝试理解一些基本概念:

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/

相关文章:

c# - 为没有字段的值对象覆盖 GetHashCode()

c++ - 从某个时候开始将变量设置为半只读

c# - 是否有与 Android 的 runOnUiThread 等效的 C#/Windows 窗体?

c# - wpf 验证 - 我怎样才能让这个代码在输入发生时触发验证(离开字段时比较)

rust - 字符串文字是不可变的吗?

arrays - 为什么没有 F# 不可变数组?

VB.Net 为什么这不是一个错误?

c# - 使类字段在事后只读

c# 对特定区域进行截图

c# - 为什么此正则表达式模式与此文本不匹配? (简单的正则表达式仅包含中间带有通配符的转义文本)