Main() 傳回值 (C# 程式設計手冊)Main() return values (C# Programming Guide)

Main 方法可以傳回 voidThe Main method can return void:

static void Main()
{
    //...
}

它也可以傳回 intIt can also return an int:

static int Main()
{
    //...
    return 0;
}

如果未使用來自 Main 的傳回值,則傳回 void 可允許使用比較簡單的程式碼。If the return value from Main is not used, returning void allows for slightly simpler code. 不過,若是傳回一個整數,可讓程式將狀態資訊傳達給其他會叫用可執行檔的程式或指令碼。However, returning an integer enables the program to communicate status information to other programs or scripts that invoke the executable file. Main 傳回的值會視為處理序的結束代碼。The return value from Main is treated as the exit code for the process. 下列範例示範如何存取來自 Main 的傳回值。The following example shows how the return value from Main can be accessed.

範例Example

此範例使用 .NET Core 命令列工具。This example uses .NET Core command line tools. 如果您不熟悉 .NET Core 命令列工具,您可以在此開始使用主題中了解這些工具。If you are unfamiliar with .NET Core command line tools, you can learn about them in this Get started topic.

修改 program.cs 中的 Main 方法,如下所示:Modify the Main method in program.cs as follows:

// Save this program as MainReturnValTest.cs.
class MainReturnValTest
{
    static int Main()
    {
        //...
        return 0;
    }
}

在 Windows 中執行程式時,任何從 Main 函式傳回的值,皆會儲存在環境變數中。When a program is executed in Windows, any value returned from the Main function is stored in an environment variable. 您可以從批次檔使用 ERRORLEVEL 或從 PowerShell 使用 $LastExitCode 來擷取此環境變數。This environment variable can be retrieved using ERRORLEVEL from a batch file, or $LastExitCode from powershell.

您可以使用 dotnet CLI dotnet build 命令來建置應用程式。You can build the application using the dotnet CLI dotnet build command.

接下來,建立 PowerShell 指令碼以執行此應用程式,並顯示結果。Next, create a Powershell script to run the application and display the result. 將下列程式碼貼入文字檔,將它儲存為 test.ps1,並放到包含專案的資料夾中。Paste the following code into a text file and save it as test.ps1 in the folder that contains the project. 在 PowerShell 命令提示字元中鍵入 test.ps1,以執行 PowerShell 指令碼。Run the powershell script by typing test.ps1 at the powershell prompt.

由於程式碼會傳回零,因為批次檔會報告成功。Because the code returns zero, the batch file will report success. 不過,如果您將 MainReturnValTest.cs 變更為傳回非零值,並重新編譯程式,則 PowerShell 指令碼的後續執行會報告失敗。However, if you change MainReturnValTest.cs to return a non-zero value and then re-compile the program, subsequent execution of the powershell script will report failure.

dotnet run
if ($LastExitCode -eq 0) {
    Write-Host "Execution succeeded"
} else
{
    Write-Host "Execution Failed"
}
Write-Host "Return value = " $LastExitCode

範例輸出Sample output

Execution succeeded
Return value = 0

Async Main 傳回值Async Main return values

Async Main 傳回值會將呼叫 Main 中非同步方法所需的未定案程式碼,移至編譯器所產生的程式碼。Async Main return values move the boilerplate code necessary for calling asynchronous methods in Main to code generated by the compiler. 之前,您需要撰寫此建構以呼叫非同步程式碼,並確保您的程式會執行到非同步作業完成為止:Previously, you would need to write this construct to call asynchronous code and ensure your program ran until the asynchronous operation completed:

public static void Main()
{
    AsyncConsoleWork().GetAwaiter().GetResult();
}

private static async Task<int> AsyncConsoleWork()
{
    // Main body here
    return 0;
}

現在,這會取代為:Now, this can be replaced by:

static async Task<int> Main(string[] args)
{
    return await AsyncConsoleWork();
}

新語法的優點是編譯器一律會產生正確的程式碼。The advantage of the new syntax is that the compiler always generates the correct code.

編譯器產生的程式碼Compiler generated code

當應用程式進入點傳回 TaskTask<int> 時,編譯器會產生新的進入點,以呼叫應用程式程式碼中宣告的進入點方法。When the application entry point returns a Task or Task<int>, the compiler generates a new entry point that calls the entry point method declared in the application code. 假設此進入點稱為 $GeneratedMain,編譯器會為這些進入點產生下列程式碼:Assuming that this entry point is called $GeneratedMain, the compiler generates the following code for these entry points:

  • static Task Main() 會導致編譯器發出 private static void $GeneratedMain() => Main().GetAwaiter().GetResult(); 的對等項目static Task Main() results in the compiler emitting the equivalent of private static void $GeneratedMain() => Main().GetAwaiter().GetResult();
  • static Task Main(string[]) 會導致編譯器發出 private static void $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult(); 的對等項目static Task Main(string[]) results in the compiler emitting the equivalent of private static void $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();
  • static Task<int> Main() 會導致編譯器發出 private static int $GeneratedMain() => Main().GetAwaiter().GetResult(); 的對等項目static Task<int> Main() results in the compiler emitting the equivalent of private static int $GeneratedMain() => Main().GetAwaiter().GetResult();
  • static Task<int> Main(string[]) 會導致編譯器發出 private static int $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult(); 的對等項目static Task<int> Main(string[]) results in the compiler emitting the equivalent of private static int $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();

注意

如果這些範例在 Main 方法上使用 async 修飾詞,編譯器會產生相同的程式碼。If the examples used async modifier on the Main method, the compiler would generate the same code.

另請參閱See also