Main() 和命令列引數 (C# 程式設計指南)Main() and command-line arguments (C# Programming Guide)

Main 方法是 C# 應用程式的進入點。The Main method is the entry point of a C# application. (程式庫和服務不需要 Main 方法做為進入點)。當應用程式啟動時,Main 方法是第一個叫用的方法。(Libraries and services do not require a Main method as an entry point.) When the application is started, the Main method is the first method that is invoked.

C# 程式中只能有一個進入點。There can only be one entry point in a C# program. 如果您具有多個含 Main 方法的類別,就必須使用 /main 編譯器選項來編譯您的程式,以指定要使用哪一個 Main 方法做為進入點。If you have more than one class that has a Main method, you must compile your program with the /main compiler option to specify which Main method to use as the entry point. 如需詳細資訊,請參閱-C# Main (編譯器選項)For more information, see -main (C# Compiler Options).

class TestClass
    static void Main(string[] args)
        // Display the number of command line arguments.


  • Main 方法是可執行程式的進入點;它是程式控制開始和結束的位置。The Main method is the entry point of an executable program; it is where the program control starts and ends.
  • Main 會宣告於類別或結構內部。Main is declared inside a class or struct. Main 必須是 static,但不必是 publicMain must be static and it need not be public. (在先前的範例中,它會接收用的預設存取權)。封入類別或結構不需要是靜態的。(In the earlier example, it receives the default access of private.) The enclosing class or struct is not required to be static.
  • Main 的傳回型別可以是 voidint,或是 TaskTask<int> (從 C# 7.1 開始)。Main can either have a void, int, or, starting with C# 7.1, Task, or Task<int> return type.
  • 只有當 Main 傳回 TaskTask<int> 時,Main 的宣告才可以包含 async 修飾詞。If and only if Main returns a Task or Task<int>, the declaration of Main may include the async modifier. 請注意,上列敘述排除了 async void Main 方法。Note that this specifically excludes an async void Main method.
  • Main 方法不一定要使用包含命令列引數的 string[] 參數來宣告。The Main method can be declared with or without a string[] parameter that contains command-line arguments. 使用 Visual Studio 建立 Windows 應用程式時,您可以手動新增參數,或使用 GetCommandLineArgs() 方法來取得命令列引數When using Visual Studio to create Windows applications, you can add the parameter manually or else use the GetCommandLineArgs() method to obtain the command-line arguments. 參數會讀入來做為以零為基礎的命令列引數。Parameters are read as zero-indexed command-line arguments. 不同于 C C++和,程式的名稱不會被視為args陣列中的第一個命令列引數,但它是GetCommandLineArgs()方法的第一個元素。Unlike C and C++, the name of the program is not treated as the first command-line argument in the args array, but it is the first element of the GetCommandLineArgs() method.

當主控台應用程式必須啟動且等待 Main 中的 await 非同步作業時,新增的 asyncTaskTask<int> 傳回型別可簡化程式碼。The addition of async and Task, Task<int> return types simplifies program code when console applications need to start and await asynchronous operations in Main.

C# 語言規格C# language specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

請參閱See also