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)
如果您查看reference source 中ThreadHelper.ThreadStart 的定义,您会看到它定义为:
internal void ThreadStart(object obj)
似乎这个 void return 被用作进程返回值,或者上面的其他方法之一正在消耗返回值并吞下它。
如果您更改项目配置并禁用托管过程,那么您将获得如下输出:
The program '[7992] TestApp.exe' has exited with code -1 (0xffffffff).
如您所愿。要禁用托管进程,请转到项目属性,然后在调试选项卡上,取消选中“启用 Visual Studio 托管进程”
退出控制台程序时,Environment.Exit() 是否比简单的 return 语句更受欢迎?因为返回语句更符合我的口味。
随你喜欢。正如 Jeppe Stig 在评论中指出的那样,有关差异的更多信息,请参阅Environment.Exit 的文档