在C#中,如果你有一个struct
,如下所示:
struct Counter
{
private int _count;
public int Value
{
get { return _count; }
}
public int Increment()
{
return ++_count;
}
}
然后您有一个类似于以下代码的程序:
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);
}
程序的输出结果将会是:1
0
这个代码似乎完全错误。我原本期望输出是两个1(如果 Counter
是一个 class
或者如果 struct Counter : ICounter
,并且 counter
是一个 ICounter
),否则应该会产生编译错误。我知道在编译时检测这个问题是非常困难的,但这个行为似乎违背了逻辑。
除了实现上的困难外,这种行为是否有其他原因呢?
readonly
数组,我仍然可以更改数组的元素。这个readonly struct
对我来说似乎是违反直觉的。它似乎是将readonly
关键字推入结构中的某种方式。 - Enigmativity