c# - 为什么不能继承静态类?

标签 c# inheritance static

我有几个类实际上不需要任何状态。从组织的角度来看,我想把它们分层次。

但是我好像不能为静态类声明继承。

类似的东西:

public static class Base
{
}

public static class Inherited : Base
{
}

将不起作用。

为什么语言的设计者关闭了这种可能性?

最佳答案

引自 here :

This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.

There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.

(Mads Torgersen, C# Language PM)

来自channel9的其他意见

Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...

Static methods are only held once in memory. There is no virtual table etc. that is created for them.

If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?

(littleguru)

作为一个有值(value)的想法,littleguru 针对此问题提供了部分“解决方法”:Singleton模式。

关于c# - 为什么不能继承静态类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/774181/

相关文章:

c# - 从 TCP 的角度来看,WCF webHTTPbinding 是什么?

c# - 接口(interface)的隐式和显式实现

C#:DbType.String 与 DbType.AnsiString

python - Django 模型继承和外键

c# - 静态方法有没有办法访问一个类的所有非静态实例?

node.js - 无法为我的静态资源 Express 设置缓存控制 header

c# - wowza streaming c# HTTP get 用于 livestreamrecord 的方法

c++ - 强制派生类实现私有(private)方法

javascript - 使用 Knockout.js 进行继承

windows - 在 Windows 上下载 QT 静态构建