为什么在函数返回其值后执行C#上的整数增量?

Est*_*bel 9 .net c# compilation function increment

为什么这两个函数返回不同的值?

当我调用此函数传递0作为参数时,它返回1

public static int IncrementByOne(int number)
{
    return (number + 1);
}
Run Code Online (Sandbox Code Playgroud)

但是,当我调用此函数传递0作为参数时它返回0,即使执行了增量并且数字变量在方法内将其值更改为1?

public static int IncrementByOne(int number)
{
    return number++;
}
Run Code Online (Sandbox Code Playgroud)

这两个函数的返回值不同的原因是什么?

Fla*_*ric 17

number++是一个后增量.它在递增之前返回其当前值.要获得与第一种方法相同的行为,请使用preincrement ++number

请参阅文档:https://msdn.microsoft.com/en-us/library/36x43w8w.aspx


xxb*_*bcc 5

所述的值后递增(后缀)++操作者是操作数的值递增前。因此,如果当前值为2,则操作员会保存2,将其递增为 ,3但会返回保存的值。

为您的功能

public static int IncrementByOne(int number)
{
    return number++;
}
Run Code Online (Sandbox Code Playgroud)

查看生成的 IL 代码,看看会发生什么:

IncrementByOne:
    IL_0000:  ldarg.0        // load 'number' onto stack
    IL_0001:  dup            // copy number - this is the reason for the
                             // postfix ++ behavior
    IL_0002:  ldc.i4.1       // load '1' onto stack
    IL_0003:  add            // add the values on top of stack (number+1)
    IL_0004:  starg.s     00 // remove result from stack and put
                             // back into 'number'
    IL_0006:  ret            // return top of stack (which is
                             // original value of `number`)
Run Code Online (Sandbox Code Playgroud)

后缀++运算符返回原始(不是递增的)值的原因是因为dup语句 - 的值number在堆栈上两次,其中一个副本通过ret函数末尾的语句保留在堆栈中,因此它被返回. 增量的结果回到number.