How does the CLR handles static classes?

烂漫一生 提交于 2019-12-22 09:43:59

问题


Can anyone explain how the CLR handles Static classes? Does the CLR create one singleton instance for handling static classes internally? If not, why do we have a static constructor in C#? (Per my understanding, we use constructors only for instantiating the class)


回答1:


First of all there is no static class in CLR. CLR doesn't know anything about static class. It is the feature of C#.

Static classes are compiled into abstract as well as sealed class. Making it abstract prevent instantiation of it and sealed prevents inheritance.

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?

No, it is abstract and can't be instantiated.

If not why we have an static constructor in 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#?




回答2:


The static constructor is called when the type is first referenced. It doesn't have to be a static class to have a static constructor.

The CLR doesn't create a singleton instance of a static class. It does keep the static variables in memory though after they are initialized.



来源:https://stackoverflow.com/questions/25643276/how-does-the-clr-handles-static-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!