在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 : ICounter和counter是ICounter)或者是编译错误.我意识到在编译时检测到这一点是一件相当困难的事情,但这种行为似乎违反了逻辑.
这种行为是否有理由超出实施难度?
structs是值类型,因此具有值类型sematics.这意味着每次访问结构时,您基本上都使用结构值的副本.
在您的示例中,您不会更改原始文件struct,只会更改其临时副本.
有关详细说明,请参见此处:
| 归档时间: |
|
| 查看次数: |
2927 次 |
| 最近记录: |