首页 > 解决方案 > 为什么使用 Environment.Exit() 时需要返回,而不是抛出异常?

问题描述

我试图更好地理解 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.
}

标签: c#exceptioncompiler-errorsreturnthrow

解决方案


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

它强制TestMethod要么返回一个值,要么抛出一个异常。调用可能终止应用程序或执行完全不同操作的方法不是从方法“返回”的有效方式。


推荐阅读