C#:为什么在只读结构突变不破? [英] C#: Why do mutations on readonly structs not break?
问题描述
在C#中,如果你有一个结构
像这样:
In C#, if you have a struct
like so:
struct Counter
{
private int _count;
public int Value
{
get { return _count; }
}
public int Increment()
{
return ++_count;
}
}
和你有一个程序,像这样:
And you have a program like so:
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);
}
该程序的输出将是:
The output of the program will be:
1
0
这似乎是完全错误的。我要么期望的输出是两个1(因为它是,如果计数
是类
或者结构计数器:ICounter
和计数
是 ICounter
),或者是编译错误。我认识到,在编译时检测到这是一个相当困难的事情,但这种行为似乎违反逻辑。
This seems completely wrong. I would either expect the output to be two 1s (as it is if Counter
is a class
or if struct Counter : ICounter
and counter
is an ICounter
) or be a compilation error. I realize that detecting this at compilation time is a rather difficult matter, but this behavior seems to violate logic.
有没有超越实现难度此行为的原因是什么?
Is there a reason for this behavior beyond implementation difficulty?
推荐答案
结构
是值类型,所以具有值类型语义学。这意味着每次访问你基本上与该结构的值的副本的工作结构的时间。
structs
are value types and therefore have a value type sematics. This means each time you access the struct you basically work with a copy of the struct's value.
在您的样品你不改变原 。结构
,但只有它的临时副本
In your sample you don't change the original struct
but only a temporary copy of it.
在这里看到进一步的解释:
See here for further explanations:
Why are mutable structs evil
这篇关于C#:为什么在只读结构突变不破?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!