解释C#中的后增量

可能重复:
C#中的行为和评估顺序

我有一些代码

static void Main(string[] args) { int j = 0; for (int i = 0; i < 10; i++) j = j++; Console.WriteLine(j); } 

为什么答案是0?

这是因为++增量的工作方式 。 在这篇MSDN文章中解释了操作的顺序。这里可以看到(如果我正在阅读关于这个错误的规范,请有人纠正我:)):

 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 

由于它是一个值对象,因此该点的两个对象( jintermediateValue )是不同的。 旧的j增加了,但因为你使用了相同的变量名,所以你输了。 我建议阅读值对象与参考对象的区别。

如果您为变量使用了单独的名称,那么您将能够更好地看到此细分。

 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; 

顾名思义,在使用该值后,增量后增量

 y = x++; 

根据C#语言规范,这相当于

 temp = x; x = x + 1; y = temp; 

适用于您的原始问题,这意味着在这些操作之后j保持不变。

 temp = j; j = j + 1; j = temp; 

您也可以使用预增量,这恰恰相反

 x = x + 1; y = x; 

要么

 y = ++x; 

请参阅MSDN上的Postfix增量和减量运算符