Why is Main method private?

余生颓废 提交于 2019-12-27 23:37:08

问题


New console project template creates a Main method like this:

class Program
{
    static void Main(string[] args)
    {
    }
}

Why is it that neither the Main method nor the Program class need to be public?


回答1:


The entry point of a program is marked with the .entrypoint IL directive. It does not matter if the method or the class is public or not, all that matters is this directive.




回答2:


The Main method shouldn't need to be called by anyone.

It is actually marked as the entry point for execution in the EXE itself, and therefore has no outside callers by default.

If you WANT, you can open it up to be called by marking public, e.g. if you are turning a console app into an API.




回答3:


Public or Private keyword doesn't make a difference in this case,it completely depends on usage and scope of the application. Use below mentioned keywords in different scenarios..

1)Public-If we want to initiate entry point by any external program,then you might need to make it public so it is accessible. 2)Private-If we know there is no external usage for the application then it is better to make it private so no external application access it.




回答4:


Yes. You can mark the main() method as public, private or protected. If you want to initiate the entry point by any external program then you might need to make it public so it is accessible. You can mark it as private if you know there is no external usage for the application then it is better to make it private so no external application access it.

public class MainMethod
{
    private  static void Main(string[] args)
    {
        Console.WriteLine("Hello World !!");
    }
}


来源:https://stackoverflow.com/questions/3110184/why-is-main-method-private

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!