为什么使用Environment.Exit()而不是引发异常时需要返回?

Jos*_*ing 2 c# compiler-errors return exception throw

我试图更好地了解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.
}
Run Code Online (Sandbox Code Playgroud)

这不会编译:

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

mm8*_*mm8 7

Environment.Exit 就编译器而言,它不过是一种方法。

它强制TestMethod返回值或引发异常。调用可能终止应用程序或执行完全不同的操作的方法不是从方法“返回”的有效方法。