在C#中解释后递增 [英] Explaining post-increment in C#
问题描述
可能重复:结果
的行为,并在C#中的评价订单
我有一些代码
static void Main(string[] args)
{
int j = 0;
for (int i = 0; i < 10; i++)
j = j++;
Console.WriteLine(j);
}
为什么答案是0?
Why answer is 0 ?
推荐答案
这是因为路的 ++递增工作。 操作的顺序MSDN文章中解释这可以在这里看到(有人请纠正我,如果我读这一个错误的规范:)):
This is because of the way the ++ increment works. The order of operations is explained in this MSDN article This can be seen here (somebody please correct me if I am reading the spec on this one wrong :)):
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
既然是一个值对象时,两个物体在这一点上(Ĵ
和 intermediateValue
)是不同的。旧的结果表明:J递增,而是因为你使用了相同的变量名,它是输给你。我建议在值对象的差异读了对参考对象,也。
Since it is a value object, the two objects (j
and intermediateValue
) at that point are different. The old j was incremented, but because you used the same variable name, it is lost to you. I would suggest reading up on the difference of value objects versus reference objects, also.
如果您曾经为变量使用单独的名称,那么你就能够看到这个故障好。
If you had used a separate name for the variable, then you would be able to see this breakdown better.
int j = 0;
int y = j++;
Console.WriteLine(j);
Console.WriteLine(y);
//Output is
// 1
// 0
如果这是一个类似的运营商一个参照对象,如预期那么这将最有可能的工作。特别指出的是如何只创建一个新的指向相同的参考。
If this were a reference object with a similar operator, then this would most likely work as expected. Especially pointing out how only a new pointer to the same reference is created.
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
回到原点,虽然:)
Back to the original point, though :)
如果你做到以下几点,那么你会得到预期的结果。
If you do the following, then you will get the expected result.
j = ++j;
这是因为增量首先出现,然后是分配。
This is because the increment occurs first, then the assignment.
然而,++可以单独使用。所以,我只想改写这个为
However, ++ can be used on its own. So, I would just rewrite this as
j++;
由于它简单地说成
As it simply translates into
j = j + 1;
这篇关于在C#中解释后递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!