为什么我不能继承静态类? [英] Why can't I inherit static classes?

查看:221
本文介绍了为什么我不能继承静态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类,并不真正需要的任何状态。但从组织一点,我想付诸层次。

I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.

但似乎我不能为静态类声明的继承。

But it seems I can't declare inheritance for static classes.

类似的东西:

public static class Base
{
}

public static class Inherited : Base
{
}

将无法工作。

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

Why have the designers of the language closed that possibility?

推荐答案

从<引文href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97955\">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托格森,C#语言PM)

通过 Channel9的

在.NET中继承只适用于实例基地。静态方法是在类型级别不是实例级别上定义。这就是为什么压倒一切不以静态方法/属性/事件工作...

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.

如果您在调用.NET实例方法,你总要给它当前实例。这是由.NET运行库藏,但它发生。 每个实例方法与第一个参数指针(引用),该方法运行的对象。这并不与静态方法发生(因为它们是在类型级别定义)。编译器应该如何决定选择方法来调用?

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)

而作为一个有价值的想法,的 littleguru 的对这个问题的部分解决办法:在辛格尔顿模式。

And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.

这篇关于为什么我不能继承静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆