我有一些代码
static void Main(string[] args)
{
int j = 0;
for (int i = 0; i < 10; i++)
j = j++;
Console.WriteLine(j);
}
为什么答案是0?
这是因为++ 增量工程 http://msdn.microsoft.com/en-us/library/36x43w8w.aspx. 这篇 MSDN 文章中解释了操作顺序 http://msdn.microsoft.com/en-us/library/aa691363这可以在这里看到(如果我阅读的规范有误,请有人纠正我:)):
int j = 2;
//Since these are value objects, these are two totally different objects now
int intermediateValue = j;
j = 2 + 1
//j is 3 at this point
j = intermediateValue;
//However j = 2 in the end
由于它是一个值对象,因此两个对象 (j
and intermediateValue
)在这一点上是不同的。旧的 j 增加了,但是因为您使用了相同的变量名,所以它丢失了。我建议阅读以下内容的区别值对象与引用对象 http://www.albahari.com/valuevsreftypes.aspx, also.
如果您为变量使用了单独的名称,那么您将能够更好地看到此细分。
int j = 0;
int y = j++;
Console.WriteLine(j);
Console.WriteLine(y);
//Output is
// 1
// 0
如果这是具有类似运算符的引用对象,那么这很可能会按预期工作。特别指出如何仅创建指向同一引用的新指针。
public class ReferenceTest
{
public int j;
}
ReferenceTest test = new ReferenceTest();
test.j = 0;
ReferenceTest test2 = test;
//test2 and test both point to the same memory location
//thus everything within them is really one and the same
test2.j++;
Console.WriteLine(test.j);
//Output: 1
回到原来的点,不过:)
如果您执行以下操作,那么您将获得预期的结果。
j = ++j;
这是因为首先发生增量,然后发生赋值。
但是,++ 可以单独使用。所以,我会把它重写为
j++;
因为它简单地翻译成
j = j + 1;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)