我正在努力更好地理解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.
}
就编译器而言,Environment.Exit
只不过是一种方法。
它强制执行TestMethod
返回值或抛出异常。调用可能终止应用程序或执行完全不同的操作的方法不是从方法“返回”的有效方法。