gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:16:13 24 4
gpt4 key购买 nike

为什么抽象类不能是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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com