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.
精彩评论