简体   繁体   English

CLR如何处理静态类?

[英]How does the CLR handles static classes?

Can anyone explain how the CLR handles Static classes? 任何人都可以解释CLR如何处理静态类? Does the CLR create one singleton instance for handling static classes internally? CLR是否为内部处理静态类创建了一个单例实例? If not, why do we have a static constructor in C#? 如果没有,为什么我们在C#中有一个静态构造函数? (Per my understanding, we use constructors only for instantiating the class) (根据我的理解,我们仅使用构造函数来实例化类)

First of all there is no static class in CLR. 首先,CLR中没有静态类。 CLR doesn't know anything about static class. CLR对静态类一无所知。 It is the feature of C#. 这是C#的特色。

Static classes are compiled into abstract as well as sealed class. 静态类被编译为abstract类和sealed类。 Making it abstract prevent instantiation of it and sealed prevents inheritance. 使其abstract化可防止实例化并sealed防止继承。

Static classes are no special, it is just a simple class with all members static. 静态类没有特殊之处,它只是一个简单的类,所有成员都是静态的。

Is, CLR internally creates one singleton instance for handling static classes? 是,CLR在内部创建一个单例实例来处理静态类吗?

No , it is abstract and can't be instantiated. ,它是抽象的,无法实例化。

If not why we have an static constructor in C#? 如果不是为什么我们在C#中有一个静态构造函数?

Static constructor will be called when type is first referenced or instantiated. 首次引用或实例化类型时,将调用静态构造函数。 It is used to initialize the static members of the class. 它用于初始化类的静态成员。

When is a static constructor called in C#? 什么时候是在C#中调用的静态构造函数?

The static constructor is called when the type is first referenced. 首次引用类型时,将调用static构造函数。 It doesn't have to be a static class to have a static constructor. 它不必是一个static构造函数的static类。

The CLR doesn't create a singleton instance of a static class. CLR不会创建static类的单例实例。 It does keep the static variables in memory though after they are initialized. 它确实在初始化后将static变量保留在内存中。

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

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