C# 为什么 Main() 方法应该是静态的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11332494/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:28:50  来源:igfitidea点击:

Why should the Main() method be static?

c#

提问by Indish

I tried to create public void Main()in C#; it says no static void Main found.
What exactly does it mean for Mainto be static? I know the code works fine for public static void Main().

我尝试public void Main()在 C# 中创建;它说没有找到 static void Main。静态
到底是什么意思Main?我知道代码适用于public static void Main().

But why does Mainhave to be static?

但为什么Main必须是static

采纳答案by Thomas Clayson

You need an entry point into your program. Static means that you can call the function without having to instantiate an object/instance of a class. It's a bit "chicken and egg"... you can't instantiate an object before you're inside the program.

您需要一个进入程序的入口点。静态意味着您可以调用该函数而无需实例化类的对象/实例。这有点“鸡与蛋”……在进入程序之前,您无法实例化对象。

A static method can be called without instantiating an object. Therefore main()needs to be static in order to allow it to be the entry to your program.

可以在不实例化对象的情况下调用静态方法。因此main()需要是静态的,以允许它成为您程序的入口。

As David says, you can just add the keyword staticto the function definition to change it. It's worth looking into static (class) methods vs instance methods, and knowing the difference can be useful at times.

正如大卫所说,您只需将关键字添加static到函数定义中即可对其进行更改。值得研究静态(类)方法与实例方法,并且有时了解差异可能很有用。

回答by Leonardo Cruz

Only the static main method can do the job because there is a convention that defines this behavior. There is not another reason.

只有静态 main 方法可以完成这项工作,因为有一个定义此行为的约定。没有其他原因。

Take a look at the C# language specification:

看看C# 语言规范

Application startupoccurs when the execution environment calls a designated method, which is referred to as the application's entry point. This entry point method is always named Main, and shall have one of the following signatures:

     static void Main() {…}  
     static void Main(string[] args) {…}  
     static int Main() {…}  
     static int Main(string[] args) {…}

As shown, the entry point can optionally return an intvalue. This return value is used in application termination (§10.2).

应用程序启动发生在执行环境调用指定的方法时,称为应用程序的入口点。此入口点方法始终命名为Main,并且应具有以下签名之一:

     static void Main() {…}  
     static void Main(string[] args) {…}  
     static int Main() {…}  
     static int Main(string[] args) {…}

如图所示,入口点可以选择返回一个int值。此返回值用于应用程序终止(第 10.2 节)。

Note: The above is quoted from the 4thedition, now labeled "historical". The current edition is worded differently.

注:以上引自4,现在标签的“历史”。当前版本的措辞有所不同。

In addition to that, the name Maincan be changed to something else. In this case a compiler option must be added telling the C# compiler to mark a different method as the entry point of the program.

除此之外,名称Main还可以更改为其他名称。在这种情况下,必须添加一个编译器选项,告诉 C# 编译器将不同的方法标记为程序的入口点。

回答by supercat

Conceptually, it would be possible for a framework to specify that rather than using a particular static method to run a program, it will instead construct a default instance of some particular class and run some particular method thereon. If one had a framework which implemented static methods by having them be instance members of a compiler-initialized singleton instance, such an approach might be entirely reasonable, since the framework would have to generate a new object instance before calling the main function in any case.

从概念上讲,框架可以指定它不是使用特定的静态方法来运行程序,而是构造某个特定类的默认实例并在其上运行某个特定方法。如果有一个框架通过让它们成为编译器初始化的单例实例的实例成员来实现静态方法,那么这种方法可能是完全合理的,因为在任何情况下,框架都必须在调用 main 函数之前生成一个新的对象实例.

If calling a static method is "easier" than constructing a new object instance and calling a method thereon, however, there isn't really much benefit to requiring that a framework use the more expensive course of action. Any code which wants to use the latter approach would be perfectly free to use:

但是,如果调用静态方法比构造新对象实例并在其上调用方法“更容易”,那么要求框架使用更昂贵的操作过程并没有太大好处。任何想要使用后一种方法的代码都可以完全免费使用:

public static void Main( [[params]] )
{
  var mainObject = new MainObject();
  mainObject.Main( [[params]] );
}

There could be some potential benefits to having the system include its own static method which looked something like:

让系统包含它自己的静态方法可能有一些潜在的好处,它看起来像:

public static void SysMain( [[params]] )
{
  using (Application app = new UserApp( [[params]] )) // UserApp derives from Application
  {
    app.Start(); // Virtual method
    app.AllowNext(); // Base method--see text
    app.Run(); // Abstract method
  }
}

where app.AllowNext()was a method to coordinate with other application instances launched at essentially the same time, to ensure that repeated attempts to launch an application in background would have their Startcalls processed strictly sequentially. Absent such a coordination scheme, however, there's not really much benefit to requiring that the framework construct an application object before running it. The cost wouldn't be huge, but without any potential identifiable benefit there's not much point in accepting even a trivial cost.

whereapp.AllowNext()是一种与基本上同时启动的其他应用程序实例协调的方法,以确保重复尝试在后台启动应用程序将Start严格按顺序处理它们的调用。然而,如果没有这样的协调方案,要求框架在运行之前构造一个应用程序对象并没有太大的好处。成本不会很大,但如果没有任何潜在的可识别好处,即使是微不足道的成本也没有多大意义。

回答by raga

There are two types of method within a class:

一个类中有两种类型的方法:

  1. Non-static method
  2. Static method
  1. 非静态方法
  2. 静态方法

// Example of static and non-static methods and how to call
namespace TestStaticVoidMain
{
    class Program
    {
        Static Void Main(string[] args)
        {
           // Instantiate or create object of the non-static method:
            Exam ob = new Exam();
            // Call the instance:
            ob.Test1();

            // Directly the call the static method by its class:
            Exam.Test2();

            Console.ReadKey();
        }
    }
    class Exam
    {
        public void Test1()
        {
            Console.WriteLine("This is a non-static method");
        }

        public static void Test2()
        {
            Console.WriteLine("This is a static method");
        }
    }
}

1. Static method:

1.静态方法:

To call a static method (function), we don't need to instantiate or create an object of that method. We can't use newkeyword because, when the class is loaded and compiled, the statickeyword by defaultinstantiates or creates an object of that class method, so that is why we directly call a static method.

要调用静态方法(函数),我们不需要实例化或创建该方法的对象。我们不能使用new关键字,因为在加载和编译类时,static关键字默认实例化或创建该类方法的对象,这就是我们直接调用静态方法的原因。

In reference to static void Main(string[] args), we already discussed static. The remainder is void Main(string[] args). voidis a data type which returns nothing. Main()is the standard entry point to execution of a C# program. The optional argument string[] argsreceives the optional "command line" parameters that the program was run with.

关于static void Main(string[] args),我们已经讨论过了static。余数为void Main(string[] args)void是一种不返回任何内容的数据类型。Main()是执行 C# 程序的标准入口点。可选参数string[] args接收程序运行时使用的可选“命令行”参数。

2. Non-static sethod:

2. 非静态设置:

To call a non-static method, we have to instantiate or create an object of the class method to call the method (function) of the class using the keyword new.

要调用非静态方法,我们必须实例化或创建类方法的对象,以使用关键字 调用类的方法(函数)new

If a class named Testhas a non-staticmethod named show(), then how it would call an instance:

如果一个名为的类Test有一个名为的非静态方法show(),那么它将如何调用实例:

// to call non-static method
Test ob=new Test();
ob.show();

回答by Nermien Barakat

During app startup, when no objects of the class have been created, the Main method must be called to begin program execution. Main is sometimes called the app's entry point. Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class. Method Main is typically declared with the header:

在应用程序启动时,当没有创建类的对象时,必须调用 Main 方法才能开始程序执行。Main 有时称为应用程序的入口点。将 Main 声明为静态允许执行环境调用 Main 而无需创建类的实例。方法 Main 通常使用标头声明:

static void Main(){..}

but also can be declared with the header:

但也可以用标头声明:

static void Main(string[] args){..}

You can declare Main with return type int (instead of void)—this can be useful if an app is executed by another app and needs to return an indication of success or failure to that other app.

您可以使用返回类型 int(而不是 void)声明 Main — 如果一个应用程序由另一个应用程序执行并且需要向该其他应用程序返回成功或失败的指示,这将非常有用。