简体   繁体   中英

What is the difference between putting a static method in a static class and putting an instance method in a static class?

What is the difference between these two classes?

public static class MyClass
{
    public static string SayHello()
    {
        return "Hello";
    }
}

public static class MyClass
{
    public string SayHello()
    {
        return "Hello";
    }
}

Is the second SayHello method also static since it is on a static class? If so, is there any reason to include the static keyword on methods when they are defined in a static class?

The second example is not even possible to do in c#, you will get compile time error:

'SayHello': cannot declare instance members in a static class

So you must declare members of static calss with static keyword.

Static classes cannot be instantiated, so your second piece of code is not compilable. A non-static method can only be accessed in an instantiated class.

"...Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created."

http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx

static classes are sealed, cannot contain instance members. Static methods are a part of the Type not the instance and static methods cannot access instance members. Static methods cannot be virtual but can be overloaded. Static methods also emit 'call' IL opcodes instead of 'callvirt'.

static classes have a static constructor that takes no arguments and it gets called before the first use of the type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM