简体   繁体   中英

Why does the Main have to be static to be able to accept command line arguments?

我是否必须有2种不同的Main方法,1种没有任何参数,1种具有string[] args但私有和静态?

Why does Main have to be static to be able to accept command line arguments ?

There, fixed that for you.

Main has to be static so that it can be called without an object instance. This is necessary because Main is called before any instances are created.

No - you only have to have one Main method. Indeed, if you have more than one static Main method in a class, I don't believe you can specify that class as an entry point.

It does have to be static though; the class can't be generic and neither can the method. It can be:

  • Any accessibility (as can the class)
  • Void or have a return value of int
  • Parameterless or have a parameter type of string[]

It has to be static and non-generic as otherwise the CLR would have to create an instance of the class or work out what type parameter you wanted, respectively. It doesn't have enough information to make either of those decisions - but it doesn't need any information for a static non-generic method in a non-generic class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM