C#:为什么readonly结构上的突变不会破坏?

Tra*_*kel 13 c# readonly

在C#中,如果你有struct这样的话:

struct Counter
{
    private int _count;

    public int Value
    {
        get { return _count; }
    }

    public int Increment()
    {
        return ++_count;
    }
}
Run Code Online (Sandbox Code Playgroud)

你有一个这样的程序:

static readonly Counter counter = new Counter();

static void Main()
{
    // print the new value from the increment function
    Console.WriteLine(counter.Increment());
    // print off the value stored in the item
    Console.WriteLine(counter.Value);
}
Run Code Online (Sandbox Code Playgroud)

该计划的输出将是:

1
0
Run Code Online (Sandbox Code Playgroud)

这似乎完全错了.我要么期望输出为两个1(因为它Counter是a class或if struct Counter : ICountercounterICounter)或者是编译错误.我意识到在编译时检测到这一点是一件相当困难的事情,但这种行为似乎违反了逻辑.

这种行为是否有理由超出实施难度?

Dir*_*mar 8

structs是值类型,因此具有值类型sematics.这意味着每次访问结构时,您基本上都使用结构值的副本.

在您的示例中,您不会更改原始文件struct,只会更改其临时副本.

有关详细说明,请参见此处:

为什么可变结构是邪恶的

  • 但是如果你带走了`readonly`,那么两个1的预期输出就会发生.所以它显然不会在那个实例中复制.这是否意味着所有在readonly结构上调用的函数都会创建结构的副本(因为C#没有变异函数的概念)? (4认同)
  • 是的,根据C#语言规范的7.5.4节就是这种情况.请参阅Eric Lippert关于该主题的帖子以获取更多详细信息. (4认同)