简体   繁体   English

为什么在C#中将静态类声明为密封和抽象?

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

This MSDN article states that static classes should be declared as sealed and abstract. 这篇MSDN文章声明静态类应声明为sealed和abstract。 I was under the impression that static classes were already sealed. 我的印象是静态类已经被封存了。 Why would you also need to declare a static class as sealed? 为什么还需要将静态类声明为密封?

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. 请记住,.NET框架支持许多不同的语言。

C# v1 did not allow 'static' keyword on class. C#v1在课堂上不允许使用'static'关键字。 So if you have a class with only static methods, it was suggested to declare it 'sealed', 'abstract' and make constructor private. 因此,如果您有一个只有静态方法的类,则建议将其声明为'sealed','abstract'并将构造函数设为私有。 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. C#v2允许类上的static关键字,因此您不必使用上述技巧来强制使用正确的用法。

  • One of the effects of marking a class as abstract is that it cannot be instantiated. 将类标记为abstract一个影响是它无法实例化。
  • One of the effects of marking a class as sealed is that is cannot be inherited. 将类标记为sealed的效果之一是不能继承。

That's what a static class actually is -- a class that cannot be instantiated and that cannot be inherited. 这就是static类实际上是一个无法实例化且无法继承的类。

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. 因此,本文并未声明您应将静态类标记为abstractsealed ,但这是静态类在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.) (如果他们没有static关键字,其他语言可能允许你这样做,虽然我对此表示怀疑,因为abstract sealed类在语义上没有多大意义。)

似乎是说如果语言不支持静态类,则使用私有构造函数将类声明为密封和抽象是静态类的替代。

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

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