C# 程序中是否可以有多个 main() 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17607951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to have more than one main() method in a C# program?
提问by social
Is it possible to have more than one main()method (with the same parameters) in a C# console application? If so, how?
main()在 C# 控制台应用程序中是否可以有多个方法(具有相同的参数)?如果是这样,如何?
采纳答案by Jainendra
You can have more than one main method, you can specify which to use as the entry point for the application by your compiler.. See thislink for more detail
您可以拥有多个主要方法,您可以指定编译器将哪个方法用作应用程序的入口点。有关更多详细信息,请参阅此链接
Example:
例子:
using System;
using System.Collections.Generic;
using System.Text;
namespace Multiple_MainClasses
{
class A
{
static void Main(string[] args)
{
Console.WriteLine("I am from Class A");
Console.ReadLine();
}
}
class B
{
static void Main(string[] args)
{
Console.WriteLine("I am from Class B");
Console.ReadLine();
}
}
}
When you will run this code, you will get compilation error. To resolve go to project properties in solution explorer or press ctrl + alt + L, go to application tab and Select Class with method which you want to execute as shown below:
当您运行此代码时,您将收到编译错误。要解决在解决方案资源管理器中转到项目属性或按 ctrl + alt + L,转到应用程序选项卡并选择要执行的方法的类,如下所示:


回答by TGH
The main method is your entry point into your application. Based on articles provided by others, it's syntactically valid to define multiple Main methods, but you have to select a single main method when running your app. I think it makes more sense to create a single main function and make it flexible by using command line args etc.
main 方法是您进入应用程序的入口点。根据其他人提供的文章,定义多个 Main 方法在语法上是有效的,但是您在运行应用程序时必须选择一个 main 方法。我认为创建单个 main 函数并通过使用命令行参数等使其灵活更有意义。
回答by Alexei Levenkov
Yes - you can specify custom entry point if you have multiple Main methods. csc /maincontains information on it:
是 - 如果您有多个 Main 方法,您可以指定自定义入口点。csc /main包含有关它的信息:
This option specifies the class that contains the entry point to the program, if more than one class contains a Main method.
如果多个类包含 Main 方法,则此选项指定包含程序入口点的类。
csc MyClssesWithMain.cs /main:OneOfTheClasses
Note: Mainmethods have to be in separate classes as you can't have 2 methods with identical signature in the same class.
注意:Main方法必须在不同的类中,因为在同一个类中不能有两个具有相同签名的方法。

