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. 有关详细信息,请参阅 /main(C# 编译器选项)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 必须是静态方法,不得为公共方法。Main 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,或者以 C# 7.1、TaskTask<int> 返回类型开头。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.
  • 使用或不使用包含命令行自变量的 string[] 参数声明 Main 方法都行。The Main method can be declared with or without a string[] parameter that contains command-line arguments. 使用 Visual Studio 创建 Windows 应用程序时,可以手动添加此形参,也可以使用 Environment 类来获取命令行实参。When using Visual Studio to create Windows applications, you can add the parameter manually or else use the Environment class to obtain the command-line arguments. 参数被读取为从零开始编制索引的命令行自变量。Parameters are read as zero-indexed command-line arguments. 与 C 和 C++ 不同,程序的名称不被视为第一个命令行自变量。Unlike C and C++, the name of the program is not treated as the first command-line argument.

添加 asyncTaskTask<int> 返回类型可简化控制台应用程序需要启动时的程序代码,以及 Main 中的 await 异步操作。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

在命令行上使用 csc.exe 生成Command-line Building With csc.exe
C# 编程指南C# Programming Guide
在 C# 程序内部Inside a C# Program