返回语句在C#中究竟做了什么?

Mik*_*y D 7 c# return return-type return-value

我很难理解退货声明究竟在做什么.例如,在这种方法中......

    public int GivePoints(int amount)
    {
        Points -= amount;
        return amount;
    }
Run Code Online (Sandbox Code Playgroud)

即使我在返回后放置任何随机整数,GivePoints方法仍然完全相同.那么返回声明在做什么呢?

小智 6

调用时返回将退出该函数.因此,返回声明下面的任何内容都不会被执行.

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


Mor*_*s S 5

Return总是会退出(离开)函数,return之后的任何内容都不会执行。

返回示例:

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

返回变量示例:

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

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

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)
Run Code Online (Sandbox Code Playgroud)


Ini*_*eer 0

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

所以在你的例子中:

int x = GivePoints(1000);
Run Code Online (Sandbox Code Playgroud)

x 将等于 1000