为什么不能在一个类扩展自己的嵌套类在C#中? [英] Why can't a class extend its own nested class in C#?

查看:82
本文介绍了为什么不能在一个类扩展自己的嵌套类在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

从编译器生成此错误

Which generates this error from the compiler:

循环基类依赖
  涉及'A'和'A·B

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

我总想表现得就像除非有关访问外部类的私有成员的特殊规则,普通班的嵌套类,但我想有两个类之间存在的一些隐性遗传?

I always figured a nested class behaved just like a regular class except with special rules concerning accessing the outer class's private members, but I guess there's some implicit inheritance occurring between the two classes?

推荐答案

还有,据我可以告诉没有涉及的隐性遗传。我本来期望这是好的 - 尽管我可以想像的怪事,如果A和B是通用

There's no implicit inheritance involved as far as I can tell. I would have expected this to be okay - although I can imagine weirdness if A and B were generic.

它在规范中第10.1.4规定:

It's specified in section 10.1.4 of the spec:

当B类从A类派生,
  它是一个一个编译时错误
  依靠B.类直接取决于
  它的直接基类(如有)和
  直接取决于在类
  它直接嵌套
(如果
  任何)。鉴于这个定义,
  一套完整的课程,其上
  类依赖是传递
  直接关闭取决于
  关系。

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限制...

That explains why the compiler is rejecting it, but not why the language prohibits it. I wonder if there's a CLI restriction...

编辑:好吧,我已经从埃里克利珀的响应。基本上,它在技术上是可能的(有没有在CLI禁止),但:

Okay, I've had a response from Eric Lippert. Basically, it would be technically possible (there's nothing in the CLI to prohibit it), but:


  • 允许,将在编译器很困难,围绕失效及订货周期目前各种假设

  • 这是一个pretty奇怪的设计决定哪一个更容易比禁止支持

这也是电子邮件线程上指出,它将使这种事情有效的:

It was also noted on the email thread that it would make this kind of thing valid:

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

...但是,这会已经(由Tinister说明)是有效的,如果b从派生。

... but that would already (as noted by Tinister) be valid if B derived from A.

嵌套+继承=奇怪...

Nesting + inheritance = oddness...

这篇关于为什么不能在一个类扩展自己的嵌套类在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆