当使用Environment.Exit()时为什么要求返回,但抛出异常时不需要?

3
我正在尝试更好地理解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.
}

1
Microsoft文档中有一节关于returnEnvironment.exit()之间的区别。 - Guy
1个回答

7

Environment.Exit只是一个方法,就编译器而言。它强制要求TestMethod 要么返回一个值,要么抛出异常。调用一个可能终止应用程序或执行完全不同操作的方法不能作为“返回”方法的有效方式。


这对我来说似乎非常合理!感谢您的建议! - Joshua Schlichting

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接