c# - 为什么抽象类不能是密封的或静态的?

标签 c# abstract-class static-classes sealed

为什么抽象类不能是sealed或者static的?

我也对这个问题感到困惑 Why declare static classes as sealed and abstract in C#? .

最佳答案

  1. static 类不能标记为sealed,因为编译器默认将其设置为sealed

    Static classes are sealed and therefore cannot be inherited.

  2. 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 a sealed or abstract modifier. Note, however, that since a static class cannot be instantiated or derived from, it behaves as if it was both sealed and abstract.

您可以阅读类被密封抽象是什么意思:

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 as sealed, abstract, and add a private 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/

相关文章:

c# - 为什么 MS 工具生成的强类型数据集不关闭流?

lucene - Lucene 对文本进行分词的过程

c# - 如何将继承一次应用于一组类

Java - 抽象类中的链接构造函数

java - 在Java中,是否可以要求接口(interface)的实现来覆盖对象方法?

Symfony2 + 注入(inject)静态类

c# - 在 C# 中使用作为参数传递的类型的方法

c# - 将 List<T> 序列化/反序列化为 JSON

c# - Xamarin 'iOS Foundation NSDate to C# DateTime conversion' 反之亦然不考虑夏令时

c# - 使用反射查看方法内部是否调用了方法