2011-08-18 252 views
0

这两个类有什么区别?将静态方法放入静态类并将实例方法放入静态类中有什么区别?

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

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

第二个SayHello方法是否也是静态的,因为它在静态类上?如果是这样,当静态类中定义静态关键字时,是否有任何理由将静态关键字包含在方法中?

+2

上面的代码不会编译。在C#中的静态类中不能有非静态方法。 – 2011-08-18 22:18:42

+0

为了将来的参考,可以很容易地在LINQPad中检查这样的代码片段,看它们是否编译,以及它们会做什么。 – StriplingWarrior

+0

是的,你至少应该试过这段代码或者做了谷歌搜索。 –

回答

8

第二个例子甚至是不可能在C#中的事,你会得到编译时错误:

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

所以你必须申报 CALSS静态的成员static关键字。

+1

现在我感觉很笨。我甚至没有考虑过是否编译。哈哈,感谢您的信息! – Chev

0

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

0

静态类是密封的,不能包含实例成员。静态方法是Type的一部分,不是实例,静态方法不能访问实例成员。静态方法不能是虚拟的,但可以重载。静态方法还会发出'调用'IL操作码而不是'callvirt'。

静态类有一个不带参数的静态构造函数,它在第一次使用类型之前被调用。

1

静态类不能实例化,所以你的第二段代码是不可编译的。非静态方法只能在实例化的类中访问。

相关问题