Why declare static classes as sealed and abstract in C#?

橙三吉。 提交于 2019-12-17 18:57:01

问题


This MSDN article states that static classes should be declared as sealed and abstract. I was under the impression that static classes were already sealed. Why would you also need to declare a static class as sealed?


回答1:


I think the pertinent bit from that article is:

"Do declare static classes as sealed and abstract, and add a private instance constructor, if your programming language does not have built-in support for static classes."

Remember, the .NET framework supports a lot of different languages.




回答2:


C# v1 did not allow 'static' keyword on class. So if you have a class with only static methods, it was suggested to declare it 'sealed', 'abstract' and make constructor private. This means that no one can instantiate your class or try to inherit from it. [It doesn't make sense to inherit from a class which has only static methods.]

C# v2 allowed the static keyword on a class so you don't have to use the above trick to enforce correct usage.




回答3:


  • One of the effects of marking a class as abstract is that it cannot be instantiated.
  • One of the effects of marking a class as sealed is that is cannot be inherited.

That's what a static class actually is -- a class that cannot be instantiated and that cannot be inherited.

So the article doesn't state you should mark your static classes as abstract and sealed additionally, but this is the way how static classes are represented in IL.

(Other languages may allow you to do this if they do not have a static keyword, although I doubt it, because an abstract sealed class doesn't make a lot of sense semantically.)




回答4:


It appears to be saying that declaring a class as sealed and abstract with a private constructor is an alternative to the static class if the language does not support static classes.



来源:https://stackoverflow.com/questions/1268983/why-declare-static-classes-as-sealed-and-abstract-in-c

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