What is the difference between static methods in a Non static class and static methods in a static class?

前端 未结 4 1683
悲&欢浪女
悲&欢浪女 2020-12-02 20:28

I have two classes Class A and ClassB:

static class ClassA
{
    static string SomeMethod()
    {
        return \"I am a Static Method\";
    }
}

class Cla         


        
相关标签:
4条回答
  • 2020-12-02 20:37

    A static class can only contain static members.

    A static method ensures that, even if you were to create multiple classB objects, they would only utilize a single, shared SomeMethod function.

    Technically, there's no difference, except that ClassA's SomeMethod must be static.

    0 讨论(0)
  • 2020-12-02 20:41

    The only difference is that static methods in a nonstatic class cannot be extension methods.


    In other words, this is invalid:

    class Test
    {
        static void getCount(this ICollection<int> collection)
        { return collection.Count; }
    }
    

    whereas this is valid:

    static class Test
    {
        static void getCount(this ICollection<int> collection)
        { return collection.Count; }
    }
    
    0 讨论(0)
  • 2020-12-02 20:44

    If you have a non-static class containing only static methods, you could create an instance of that class. But you can't use that instance meaningfully. NB: when you don't define a constructor, the compiler adds one for you.

    A static class does not have a constructor, so you can't create an instance of it. Also the compiler gives an error when you add an instance method to it (where you meant a static method).

    See also docs.

    0 讨论(0)
  • 2020-12-02 20:49

    A static method belongs to the class and a non-static method belongs to an object of a class. That is, a non-static method can only be called on an object of a class that it belongs to. A static method can access only static members. A non-static method can access both static and non-static members because at the time when the static method is called, the class might not be instantiated (if it is called on the class itself). In the other case, a non-static method can only be called when the class has already been instantiated. A static method is shared by all instances of the class. Whenever a method is called in C++/Java/C#, an implicit argument (the ‘this’ reference) is passed along with/without the other parameters. In case of a static method call, the ‘this’ reference is not passed as static methods belong to a class and hence do not have the ‘this’ reference.

    0 讨论(0)
提交回复
热议问题