简体   繁体   中英

C# inheritence and static classes

为什么不能将静态类继承为普通类?

If B inherits from (is a subclass of) A, that means an instance of B can be stored in a variable of type A, and its virtual methods will call those of class B.

For static classes, you don't have the concept of an instance of the class, so there's no way to inherit. You might have better luck with a static (singleton) reference to a regular class.

From Static Classes and Static Class Members (C# Programming Guide)

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can contain a static constructor.

作为从静态类继承的替代方法,可以将扩展方法分配给接口。

You can not inherit a static class - The reason is simple. Static classes are marked as abstract and sealed in compiled IL which can be neither instantiated nor inherited .

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)

Source: Why can't I inherit static classes?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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