What is the difference between public static void Main() and private static void Main() in a C# console application?

前端 未结 10 1165
梦毁少年i
梦毁少年i 2021-02-06 20:32

What is the difference between

public static void Main()

and

private static void Main()

in a C# console appli

10条回答
  •  鱼传尺愫
    2021-02-06 21:13

    The private or public statement is it's access modifier, a private access modifier makes it inaccessible to external objects where a public access modifier makes it accessible to external objects. example usage:

    Say we have a class:

    class myClass{
        public void test(){
            //do something
        }
    }
    

    We create an instance of that class:

    myClass mClass=new myClass();
    

    To access it's member function you would go:

    mClass.test();
    

    If it had a private access modifier, you'd get a compile error saying it's inaccessible.

    And just for knowledge's sake, to access a member without creating an instance of a class, you'd also make that member static, eg:

    class myClass{
        public static void test(){
            //do something
        }
    }
    

    So to access it now, you'd just simply do:

    myClass.test();
    

    (Note that any members accessed in a static member should also be static)

提交回复
热议问题