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

前端 未结 6 1478
半阙折子戏
半阙折子戏 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:29

    Regarding questions about what I was attempting to do:

    Basically, I wanted to create a class that had a composition relationship with itself, but I didn't want to have the contained object to contain other objects and therefore create a chain with many "A has-a A has-a A has-a A has-a..." relationships. So my thought at the time was do something like this:

    public class A : A.AA
    {
        public class AA
        {
            // All of the class's logic
        }
    
        private AA _containedObject;
    }
    

    Which at the time seemed pretty slick but in retrospect I'm not so sure...

    I had rummaged through Google and didn't find any good discussion on it so I thought I'd post it here.

    However, within the comments of a post at Eric Lippert's Blog he gives examples of a class implementing a nested interface as well as a class implementing a generic interface with a nested class as the type argument (which doesn't compile and he calls a "bug" in the current compiler). Both of those examples concern interfaces so I was wondering if there was some special rules with nested classes. And it seems there are.

提交回复
热议问题