作者:心雨00937 | 来源:互联网 | 2023-05-26 13:09
你能不能帮我理解为什么变量a
在第一种情况下没有增加但是在第二种情况下呢?
情况1:
int a = 10;
a = a++;
Console.WriteLine(a); //prints 10
案例2:
int a = 10;
int c = a++;
Console.WriteLine(a); //prints 11
我已经完成了其他类似的问题,但找不到任何具体细节.
更新1:我认为程序如何流动
情况1:
1. 'a' is assigned 10
2. 'a' is assigned 10 before increment happens
3. 'a' is incremented by 1 (Why doesn't this step affect the final value of 'a'?)
4. 'a' is printed --> 10
案例2:
1. 'a' is assigned 10
2. 'c' is assigned 10 before 'a' is incremented
3. 'a' is incremented by 1 (Why does the increment of 'a' work here?)
4. 'a' is printed --> 11
更新2:感谢所有答案,我想我已经理解了,如果我错了,请纠正我.
情况1:
1. `a` is assigned 10
2. Compiler evaluates `a++`, stores old value 10 and new value 11 as well. Since it's a post increment operation, assigns the old value to `a`. What i thought was, compiler would assign the old value 10 first and evaluate the `++` operation later. This is where i was wrong, compiler evaluates the RHS beforehand and assigns the value based on the operator.
4. 'a' is printed --> 10
案例2:
1. `a` is assigned 10
2. Compiler evaluates `a++`, stores old value 10 and new value 11 as well. Since it's a post increment operation, assigns the old value to `c` but value of `a` is preserved with `11`.
4. 'a' is printed --> 11
Richard Schn..
6
第一种情况a = a++
是后增量.其中说添加1 a
但返回之前的值,a
然后将之前的结果存回a
.这基本上是一个无操作.
如果它是预增量a = ++a
,那么a
将是11.
1> Richard Schn..:
第一种情况a = a++
是后增量.其中说添加1 a
但返回之前的值,a
然后将之前的结果存回a
.这基本上是一个无操作.
如果它是预增量a = ++a
,那么a
将是11.
2> Ondrej Janac..:
对我来说,了解某些行为的最佳方法是检查IL生成.在你的第一种情况下
IL_0001: ldc.i4.s 0A // stack: 10
IL_0003: stloc.0 // a = 10, stack: empty
IL_0004: ldloc.0 // stack: 10
IL_0005: dup // stack: 10, 10
IL_0006: ldc.i4.1 // stack: 10, 10, 1
IL_0007: add // stack: 10, 11
IL_0008: stloc.0 // a = 11, stack: 10
IL_0009: stloc.0 // a = 10, stack: empty
IL_000A: ldloc.0 // stack: 10
IL_000B: call System.Console.WriteLine
您可以看到堆栈上仍然存在原始值,因此创建的11最终会被覆盖.
让我试着用简单的话来解释它.
当您为变量(a = a++
)赋值时,首先会对赋值的整个右侧进行求值,以保证正确的值,就是这样.所以没有你得到10,应用程序继续并在执行下一行时增加值.
现在,想象一下后增量作为某人,他首先递增一个值,但给了他的世界,你将从表达式中获得原始值.现在你应该明白为什么11被覆盖了.增量先行,最后,你得到承诺的原始价值(正如IL证明的那样).