return(C# 参考)return (C# Reference)

return 语句可终止它所在的方法的执行,并将控制权返回给调用方法。The return statement terminates execution of the method in which it appears and returns control to the calling method. 它还可以返回可选值。It can also return an optional value. 如果方法是 void 类型,则 return 语句可以省略。If the method is a void type, the return statement can be omitted.

如果 return 语句位于 try 块中,则 finally 块(如果存在)会在控制权返回给调用方法之前进行执行。If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method.

示例Example

在下面的示例中,方法 CalculateArea() 将局部变量 area 作为 double 值返回。In the following example, the method CalculateArea() returns the local variable area as a double value.

class ReturnTest
{
    static double CalculateArea(int r)
    {
        double area = r * r * Math.PI;
        return area;
    }

    static void Main()
    {
        int radius = 5;
        double result = CalculateArea(radius);
        Console.WriteLine("The area is {0:0.00}", result);

        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output: The area is 78.54

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also