【问题标题】:Why the increment of an integer on C# is executed after a function return its value?为什么在函数返回值后执行 C# 上的整数增量?
【发布时间】:2017-01-17 15:49:33
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: c# .net function compilation increment


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      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

      【讨论】:

      • 投反对票的人,想解释一下你的投票吗?如果您认为此答案有问题,请告诉我。
      • 代码和你对它的描述是相反的。你说值是在增量之前返回的,但是阅读代码。 ret 发生在 增量之后!
      • 正确的说法是“操作的值是操作数在递增之前的值”。所以顺序是:评估、递增、返回。这一切都清楚地记录在规范中。
      • @EricLippert 好的,我可能措辞有误。我以为我写对了。我会更新答案。
      • 在方法返回时,堆栈上的值是number 增量之前的值(因此是返回值)。增加的值已经存储在本地,但没有压入堆栈。
      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-10
          • 1970-01-01
          • 2021-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多