简体   繁体   English

为什么静态类密封?

[英]Why are static classes sealed?

I understand what static classes and sealed classes are, and I regularly use extension methods, I'm just wondering—does anyone know why static classes are sealed in C#? 我理解静态类和密封类是什么,我经常使用扩展方法,我只是想知道 - 有谁知道为什么静态类被密封在C#中?

I've looked at MSDN and the C# language specification, but it never really says why they're sealed. 我已经看过MSDN和C#语言规范,但它从未真正说明为什么它们被密封了。

Why shouldn't we be able to inherit from static classes and override static members, etc.? 为什么我们不能继承静态类并覆盖静态成员等?

Edit: 编辑:

I appreciate your answers, but you're still talking about what a static class is . 我很感激你的答案,但你还在谈论静态类什么。 I know why I can't override its methods. 我知道为什么我不能覆盖它的方法。 But I'm asking why did they make it that way? 但我问他们为什么这么做?

Are vtables really that expensive? vtable真的那么贵吗? Why design a langauge so static classes are literally static? 为什么设计一个语言,所以静态类是字面上的静态? Is it just for tradition? 它只是为了传统吗? Is there another advantage I'm not seeing? 我还没有看到另一个优势吗?

(I have the sneaking suspicion I'm fundamentally misunderstanding the point of static classes.) (我有偷偷摸摸的怀疑,我从根本上误解了静态课程的重点。)

You can't inherit static classes because you can't override static members. 您不能继承静态类,因为您无法覆盖静态成员。 You can't override static members because the entire concept of overriding members is dependent on virtual dispatch on the type of the implicit parameter, and static members have no implicit parameter to dispatch on. 您不能覆盖静态成员,因为覆盖成员的整个概念依赖于隐式参数类型的虚拟分派,而静态成员没有要调度的隐式参数。

Sealing a class means that you cannot use it as a superclass. 密封类意味着您不能将其用作超类。 Making a class static makes them useless as base classes, because they cannot have overridable methods. 使类static使它们无法用作基类,因为它们不能具有可覆盖的方法。 Therefore, deriving from a static class has questionable value: one could argue that you could share protected methods from a static base, but then it is a "one-way street", because derived classes cannot alter functionality of their bases by providing useful overrides. 因此,从静态类派生有可疑的价值:有人可能会争辩说你可以从静态基础共享受保护的方法,但是它是一个“单行道”,因为派生类不能通过提供有用的覆盖来改变其基础的功能。

This boils down the utility of static classes to a namespace-like holder of methods and their associated static data. 这将静态类的实用程序归结为类似命名空间的方法持有者及其关联的静态数据。 Letting such classes inherit other static classes would make this purpose less clear while adding very little in terms of functionality or convenience. 让这些类继承其他静态类会使这个目的不那么清晰,而在功能或方便性方面添加很少。

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

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