c# - 为什么使用 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.
}
解决方案
Environment.Exit
就编译器而言,它只不过是一种方法。
它强制TestMethod
要么返回一个值,要么抛出一个异常。调用可能终止应用程序或执行完全不同操作的方法不是从方法“返回”的有效方式。
推荐阅读
- java - Java Servlet - 使用 HashMap 存储用户然后保存到文件并读取
- api - 任何人都可以帮助我处理每个事件响应的奇迹 api 字符吗?
- java - 如何使用 Spring Security 实现混合身份验证,提供带有 WAFFLE 的单点登录和基于表单的身份验证?
- r - 我应该如何解释这段代码:select(-Segment, -Units01)
- python - 此代码无法显示 KeyError: 'Percentage'
- javascript - 从 data.json 文件 (expressJS) 将数据解析为 index.ejs
- python - Django - QuerySet 在 permissions.py 中不可迭代
- javascript - 如何使用 tab 键获取当前选择的元素?
- php - wav 文件无法在浏览器中播放
- docker - docker日志文件和缓存内存之间有关系吗?