【发布时间】:2019-09-08 17:49:34
【问题描述】:
我试图更好地理解 C# 的编译器。它坚持所有代码路径都必须返回一个值,我认为这很公平。
它还认识到,如果在需要返回值的路径中引发异常,则在该处返回某些内容是没有意义的。这也是有道理的。
我的问题是:为什么这也不适用于以更优雅的方式退出程序?例如Environment.Exit()
-示例-
这将编译:
private string TestMethod(int x, int y)
{
if (x == y)
{
return "this is a string";
}
throw new Exception();
// No point in a return after this, it could never be reached.
}
这不会编译:
private string TestMethod(int x, int y)
{
if (x == y)
{
return "this is a string";
}
Environment.Exit(1);
// This will not compile.
// "Not all code paths return a value"
// But, the code would never make it to the return here.
}
【问题讨论】:
-
Microsoft docs 作为关于
return和Environment.exit()之间区别的部分
标签: c# exception compiler-errors return throw