为什么抽象类不能是sealed或者static的?
我也对这个问题感到困惑 Why declare static classes as sealed and abstract in C#? .
最佳答案
static
类不能标记为sealed
,因为编译器默认将其设置为sealed
。Static classes are sealed and therefore cannot be inherited.
static
类不能被标记为abstract
,因为它毫无意义。当您希望所有派生类都实现相同的逻辑部分时,abstract
类很有意义。但是由于无法派生static
类,因此其他类无法实现这些差距。They cannot inherit from any class except
Object
.
均引自 Static Classes and Static Class Members (C# Programming Guide) .
C# 规范对此更详细一些:
10.1.1.3 Static classes
A
static
class may not include asealed
orabstract
modifier. Note, however, that since astatic
class cannot be instantiated or derived from, it behaves as if it was bothsealed
andabstract
.
您可以阅读类被密封
或抽象
是什么意思:
An abstract class cannot be instantiated directly, and it is a compile-time error to use the new operator on an abstract class
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class.
更新
关于您提到的查询中链接的一篇文章的词 ( Static Class Design )。它已经在该问题的已接受答案中说明。如果你仔细阅读,你会发现:
√ DO declare
static
classes assealed
,abstract
, and add aprivate
instance constructor if your programming language does not have built-in support for static classes.
.NET(C# 也是如此)确实内置了对静态类的支持,因此您不必(甚至不能)通过标记使您的类成为伪静态它既是密封的
又是抽象的
。
关于c# - 为什么抽象类不能是密封的或静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20965626/