【问题标题】:Why is a return required when Environment.Exit() is used, but not for a thrown exception?为什么使用 Environment.Exit() 时需要返回,而不是抛出异常?
【发布时间】: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 作为关于returnEnvironment.exit() 之间区别的部分

标签: c# exception compiler-errors return throw


【解决方案1】:

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

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

【讨论】:

  • 这对我来说似乎很合理!感谢您的意见!
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2021-06-30
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多