开发者

C# comparing private static and public static method

开发者 https://www.devze.com 2023-01-30 09:25 出处:网络
In C#, what is the dif开发者_Python百科ference between methods that are markedpublic staticand methods marked asprivate static?

In C#, what is the dif开发者_Python百科ference between methods that are markedpublic staticand methods marked asprivate static?

How are they allocated and accessed?


A private static method can only be accessed within the class that it's defined in. A public static method can be accessed outside of the class.

public class MyClass
{ 
    private static void MyPrivateMethod()
    {
        // do stuff
    }

    public static void MyPublicMethod()
    {
        // do stuff
    }
}

public class SomeOtherClass
{
    static void main(string[] args)
    {
         MyClass.MyPrivateMethod(); // invalid - this method is not visible

         MyClass.MyPublicMethod(); // valid - this method is public, thus visible
    }
}

As far as memory allocation goes, see here:

Where are methods stored in memory?


Private static methods can only be accessed by other methods in that class. Public static methods are pretty much global in access.


Static methods are applied at a class level, ie, an object is not required to access them. The only difference between public and private methods is accessibility.

  • Private methods are visible only to other methods within that class.
  • Public methods are visible to any other class.

    Static methods can be accessed by both static and non-static methods.

  • 0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消