代码之家  ›  专栏  ›  技术社区  ›  FrantiÅ¡ek Žiačik

为什么主方法是私有的?

  •  40
  • FrantiÅ¡ek Žiačik  · 技术社区  · 14 年前

    新的控制台项目模板创建如下的主要方法:

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

    为什么这两者都不是 Main 方法也不 Program 班级需要公开?

    4 回复  |  直到 6 年前
        1
  •  45
  •   dtb    14 年前

    程序的入口点用 .entrypoint IL指令。It does not matter if the method or the class is public or not, all that matters is this directive.

        2
  •  19
  •   John Gietzen    14 年前

    这个 Main 任何人都不需要调用方法。

    它实际上被标记为在exe本身中执行的入口点,因此默认情况下没有外部调用程序。

    如果你 想要 ,您可以通过标记打开它来调用 public 例如,如果您要将控制台应用程序转换为API。

        3
  •  0
  •   Aakash Dhoundiyal    11 年前

    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如果我们想通过任何外部程序启动入口点,那么您可能需要将其公开以便访问。 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
  •  -1
  •   TheLethalCoder    6 年前

    对。你可以标记 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 !!");
        }
    }