Why can't a class extend its own nested class in C#?

前端 未结 6 1482
半阙折子戏
半阙折子戏 2020-12-08 14:25

For example:

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

Which generates this error from the compiler:

Circular

6条回答
  •  一生所求
    2020-12-08 14:47

    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.

    It's specified in section 10.1.4 of the spec:

    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.

    I've highlighted the relevant section.

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

    EDIT: 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:

    • Allowing it would be difficult in the compiler, invalidating various current assumptions around ordering and cycles
    • It's a pretty odd design decision which is easier to prohibit than to support

    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();
    

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

    Nesting + inheritance = oddness...

提交回复
热议问题