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()比簡單返回聲明?因爲退貨聲明對我的品味更加簡潔。
無論你喜歡什麼。正如Jeppe Stig在評論中指出的,有關這些差異的更多信息,請參見Environment.Exit
的文檔
另請參見['Environment.Exit(Int32)'方法文檔](https://msdn.microsoft.com /en-us/library/system.environment.exit.aspx)獲取差異列表。 –
@JeppeStigNielsen好點。如果您的評論消失,請添加一條關於它的註釋。 – theB
*首選*從主返回退出。調用'Environment.Exit'是一種破解,在設計良好的應用程序中不應該是必需的。 –