c# - 为什么一个类不能在 C# 中扩展它自己的嵌套类?

标签 c# nested-class

例如:

public class A : A.B
{
    public class B { }
}

从编译器生成此错误:

Circular base class dependency involving 'A' and 'A.B'

除了关于访问外部类的私有(private)成员的特殊规则外,我一直认为嵌套类的行为就像普通类一样,但我猜这两个类之间是否存在一些隐式继承?

最佳答案

据我所知,不涉及隐式继承。我原以为这没问题 - 尽管我可以想象如果 A 和 B 是通用的会很奇怪。

它在规范的第 10.1.4 节中指定:

When a class B derives from a class A, it is a compile-time error for A to depend on B. A class directly depends on its direct base class (if any) and directly depends on the class within which it is immediately nested (if any). Given this definition, the complete set of classes upon which a class depends is the transitive closure of the directly depends on relationship.

我已经突出显示了相关部分。

这解释了为什么编译器拒绝它,但没有解释为什么语言禁止它。我想知道是否有 CLI 限制...

编辑:好的,我收到了 Eric Lippert 的回复。基本上,这在技术上是可行的(CLI 中没有任何内容可以禁止它),但是:

  • 在编译器中允许它会很困难,使当前关于顺序和周期的各种假设无效
  • 这是一个非常奇怪的设计决定,禁止比支持更容易

在电子邮件线程中还指出,它会使这种事情有效:

A.B x = new A.B.B.B.B.B.B.B.B.B.B.B.B();

...但是如果 B 派生自 A,那已经(如 Tinister 所指出的)有效。

嵌套+继承=奇怪...

关于c# - 为什么一个类不能在 C# 中扩展它自己的嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/265585/

相关文章:

c# - 段落列表不包含完整内容

c# - JSON字符串格式到URL编码c#

c# - 让设计者为 UserControl 的简单 List 属性生成 AddRange

java - 嵌套类匿名类

c++ - 如何从C++中的嵌套类调用变量

PHP 嵌套类工作......有点?

c# - XML反序列化: working with list

java - for循环中嵌套类,会不会有n个类的实例?

c++ - Visual Studio 2005 c++ 继承错误的解决方法

c# - LINQ 一次更新多个元素