退货类型
方法可以返回任何内容(void
)或指定类型的值:
// If you don't want to return a value, use void as return type.
static void ReturnsNothing() {
Console.WriteLine("Returns nothing");
}
// If you want to return a value, you need to specify its type.
static string ReturnsHelloWorld() {
return "Hello World";
}
如果你的方法指定了返回值,则该方法必须返回一个值。你可以使用 return
语句执行此操作。一旦达到了 return
语句,它就会返回指定的值,并且它之后的任何代码都将不再运行(异常是 finally
块,它将在方法返回之前执行)。
如果你的方法什么都没有返回(void
),如果你想立即从方法返回,你仍然可以使用没有值的 return
语句。在这种方法结束时,虽然不需要 return
语句。
有效 return
语句的示例:
return;
return 0;
return x * 2;
return Console.ReadLine();
抛出异常可以在不返回值的情况下结束方法执行。此外,还有迭代器块,其中返回值是使用 yield 关键字生成的,但这些是特殊情况,此时将不再解释。