简体   繁体   English

将静态方法放入静态类与将实例方法放入静态类有什么区别?

[英]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? 由于第二个SayHello方法在静态类上,因此它也是静态的吗? If so, is there any reason to include the static keyword on methods when they are defined in a static class? 如果是这样,当在静态类中定义方法时,是否有任何理由在方法上包括static关键字?

The second example is not even possible to do in c#, you will get compile time error: 第二个示例甚至无法在c#中完成,您将得到编译时错误:

'SayHello': cannot declare instance members in a static class 'SayHello':无法在静态类中声明实例成员

So you must declare members of static calss with static keyword. 因此,您必须使用static关键字声明static calss的成员。

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 http://msdn.microsoft.com/zh-CN/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. 静态方法是Type的一部分,而不是实例,并且静态方法无法访问实例成员。 Static methods cannot be virtual but can be overloaded. 静态方法不能是虚拟的,但是可以重载。 Static methods also emit 'call' IL opcodes instead of 'callvirt'. 静态方法还会发出“ call” IL操作码,而不是“ callvirt”。

static classes have a static constructor that takes no arguments and it gets called before the first use of the type. 静态类具有一个不带任何参数的静态构造函数,并且在首次使用该类型之前会被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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