【问题标题】:What exactly does a return statement do in C#? [closed]C# 中的 return 语句究竟做了什么? [关闭]
【发布时间】:2013-03-06 02:01:58
【问题描述】:

我很难理解 return 语句到底在做什么。比如在这个方法中……

    public int GivePoints(int amount)
    {
        Points -= amount;
        return amount;
    }

即使我在返回后放置任何随机整数,GivePoints 方法仍然会做同样的事情。那么 return 语句在做什么呢?

【问题讨论】:

  • 我不确定如何回答这个问题,除了说它返回一个值给调用者方法。

标签: c# return return-value return-type


【解决方案1】:

return 调用时会退出该函数。因此,return 语句下面的任何内容都不会被执行。

基本上,return 表示该函数应该执行的任何操作都已执行,并将该操作的结果传回(如果适用)给调用者。

【讨论】:

    【解决方案2】:

    Return 将始终退出(离开)函数,返回后的任何内容都不会执行。

    返回示例:

    public int GivePoints(int amount)
    {
        Points -= amount;
        return; //this means exit the function now.
    }
    

    返回变量示例:

    public int GivePoints(int amount)
    {
        Points -= amount;
        return amount; //this means exit the function and take along 'amount'
    }
    

    返回一个变量示例并捕获返回的变量:

    public int GivePoints(int amount)
    {
        Points -= amount;
        return amount; //this means exit the function and take along 'amount'
    }
    
    int IamCatchingWhateverGotReturned = GivePoints(1000); //catch the returned variable (in our case amount)
    

    【讨论】:

    • 第一个例子编译失败(函数必须返回int值)
    【解决方案3】:

    return 会将控制权从当前方法返回给调用者,并将随它一起发送的任何参数传回。在您的示例中,GivePoints 被定义为返回一个整数,并接受一个整数作为参数。在您的示例中,返回的值实际上与参数值相同。

    在调用定义的方法的代码中的其他位置使用返回值,在此示例中为 GivePoints

    int currentPoints = GivePoints(1);
    

    意味着currentPoints 被赋值为 1。

    这分解为GivePoints 被评估。 GivePoints 的评估基于方法返回的内容。 GivePoints 返回输入,因此,GivePoints 在上面的示例中将计算为 1。

    【讨论】:

    • +1 另一个值得一提的好东西可能是Stack 概念:方法在堆栈上调用,return 语句退出当前方法,返回控制流(通常是一个值) 回到堆栈上的前一个方法。
    • 此外,不会评估运行 return 语句后出现的代码。这就是您的“随机整数”值被忽略的原因。
    【解决方案4】:

    在您的示例中,该函数返回您发送给它的确切数字。在这种情况下,无论您作为amount 传递什么值。因此,您当前代码中的返回有点毫无意义。

    所以在你的例子中:

    int x = GivePoints(1000);
    

    x 等于 1000

    【讨论】:

    • 你应该解释一下return之后的任何东西都不会执行,这似乎是提问者的真正难题。
    【解决方案5】:

    只是对你最初目标的猜测

    public int GivePoints(int amount)
    {
        Points -= amount;
        return Points;
    }
    

    所以 return 将返回 Points 的更新值

    如果不是你的情况,代码应该是

    public void GivePoints(int amount)
    {
        Points -= amount;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-19
      • 2015-01-10
      • 2021-08-22
      • 2013-09-29
      • 2011-05-09
      • 2014-09-13
      • 2012-07-23
      • 2016-09-10
      • 2023-03-15
      相关资源
      最近更新 更多