What is the difference between static methods in a

2019-01-11 00:26发布

问题:

I have two classes Class A and ClassB:

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

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

I want to know what is the difference between ClassA.SomeMethod(); and ClassB.SomeMethod();

When they both can be accessed without creating an instance of the class, why do we need to create a static class instead of just using a non static class and declaring the methods as static?

回答1:

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; }
}


回答2:

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.



回答3:

Check this links

Static Classes

Static vs Non-Static Methods

Regards



回答4:

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).



回答5:

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.