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

问题描述 投票:7回答:4

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

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

public static int IncrementByOne(int number)
{
    return (number + 1);
}

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

public static int IncrementByOne(int number)
{
    return number++;
}

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

c# .net function compilation increment
4个回答
15
投票

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

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


3
投票

post-increment (postfix) ++ operator的值是操作数增加之前的值。因此,如果当前值为2,则运算符保存2,将其递增到3但返回保存的值。

为了你的功能

public static int IncrementByOne(int number)
{
    return number++;
}

查看生成的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`)

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


1
投票

或者,指出穴居人的方法......

public static int IncrementByOne(int number)
{
    number++;
    return number;
}

0
投票

最后一个函数后递增数;如果你想立即递增值,你可以尝试return ++number;

© www.soinside.com 2019 - 2024. All rights reserved.