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

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

    I was able to avoid this (at least with interfaces) by inheriting from a separate class containing the nested interfaces. (In my scenario I am also returning references to these interfaces.)

    Instead of:

    public class MyClass :
       MyClass.Interface
    where T1 : ...
    where T2 : ... 
    where T3 : ... {
       public interface Interface { Interface SomeMethod(); }
    
       Interface Interface.SomeMethod() {
          ...
       }
    }
    
    // compile error: Circular base class dependency
    

    Do something like this:

    public sealed class MyClassInterfaces
    where T1 : ...
    where T2 : ... 
    where T3 : ... {
       public interface Interface { Interface SomeMethod(); }
    }
    
    sealed class MyClass :
       MyClassInterfaces.Interface
    where T1 : ...
    where T2 : ... 
    where T3 : ... {
       MyClassInterfaces.Interface
       MyClassInterfaces.Interface.SomeMethod() {
          ...
       }
    }
    

    To avoid the ugliness with explicit interface implementations, you can also inherit from the other class, though that wouldn't work if you were trying to inherit from a nested class, since you can't inherit from both classes.

    public abstract class MyClassInterfaces
    where T1 : ...
    where T2 : ... 
    where T3 : ... {
       public interface Interface { Interface SomeMethod(); }
    }
    
    sealed class MyClass :
       MyClassInterfaces,
       MyClassInterfaces.Interface
    where T1 : ...
    where T2 : ... 
    where T3 : ... {
       Interface Interface.SomeMethod() {
          ...
       }
    }
    

提交回复
热议问题