【发布时间】:2014-05-26 23:14:51
【问题描述】:
我记得在某处读到过,对于变量int i,++i 和 i++ 都会在 C# 中生成一个临时变量。有谁知道为什么会这样?它们的性能是否相同?
更新
所以从 Eric Lippert 在副本中的回答来看,预增量的步骤如下:
对于预增量
1) x 被评估以产生变量
2) 变量的值被复制到一个临时位置
3) 临时值递增以产生新值(不会覆盖临时值!)
4) 新值存储在变量中
5) 运算结果为新值
为什么需要第 2 步?为什么不就地增加变量呢?
【问题讨论】:
-
我猜他们是一样的。
-
++i 不应该创建临时文件。你从哪里得到这些信息的?
-
@Fedor,Eric Lippert 在他对副本的回答中这么说。
-
它创建临时,eric explains it here
-
@Ned,我相信 Eric 会解释它:
x could be volatile and changing on another thread; the value returned by x++ is not the current value of x, it is what x was assigned, and that could be different。在 preincrement 的情况下,同样的原则也适用(变量可能是 volatile 或者另一个线程可能正在改变它)。
标签: c#