Main() 的返回值与 Environment.ExitCode 是否有些不同?
不,他们是一样的,去同一个地方。您可以通过尝试仅返回 -1 或设置Environment.ExitCode
为 -1 的控制台应用程序来看到这一点。您将看到您使用的任何方法都可以正常工作并%ERRORLEVEL%
正确设置。
VS2015有什么方法可以轻松找出Main()方法的返回值?
首先,简要介绍一下似乎正在发生的事情。这是使用默认项目设置创建的控制台应用程序的堆栈跟踪:
TestApp.exe!TestApp.Program.Main(string[] args)
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args)
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state)
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart()
请注意,VS 主机进程在那里。禁用 VS 托管进程后,堆栈跟踪(使用相同的选项)如下所示:
TestApp.exe!TestApp.Program.Main(string[] args)
如果您查看参考源ThreadHelper.ThreadStart
中的定义,您会看到它定义为:
internal void ThreadStart(object obj)
似乎这个 void 返回被用作进程返回值,或者上面的其他方法之一正在消耗返回值并吞下它。
如果您更改项目配置并禁用托管过程,那么您将获得如下输出:
The program '[7992] TestApp.exe' has exited with code -1 (0xffffffff).
如你所料。要禁用托管进程,请转到项目属性,然后在调试选项卡上,取消选中“启用 Visual Studio 托管进程”
退出控制台程序时,Environment.Exit() 是否比简单的 return 语句更受欢迎?因为退货声明更符合我的口味。
无论您喜欢哪个。正如 Jeppe Stig 在评论中指出的那样,有关差异的更多信息,请参阅文档Environment.Exit