例如:
public class A : A.B
{
public class B { }
}
这会导致编译器生成以下错误:
涉及“ A”和“ A.B”的循环基类依赖关系
我一直认为嵌套类的行为就像常规类一样,只是有关于访问外部类私有成员的特殊规则,但我猜在这两个类之间发生了一些隐式继承?
public class A : A.B
{
public class B { }
}
这会导致编译器生成以下错误:
涉及“ A”和“ A.B”的循环基类依赖关系
我一直认为嵌套类的行为就像常规类一样,只是有关于访问外部类私有成员的特殊规则,但我猜在这两个类之间发生了一些隐式继承?
A.B x = new A.B.B.B.B.B.B.B.B.B.B.B.B();
... 但是如果B源自A,那么这已经是有效的(如Tinister所指出的)。
嵌套+继承=奇怪的事情...
这不仅仅是C#的问题,更是编译器的问题。编译器的工作之一就是将类在内存中进行布局,包括一些基本数据类型、指针、函数指针和其他类。
它无法构建类A的布局,直到它知道类B的布局是什么。它不能知道类B的布局是什么,直到它完成了类A的布局。循环依赖。
public class A : A.AA
{
public class AA
{
// All of the class's logic
}
private AA _containedObject;
}
当时看起来很不错,但回想起来我并不确定...
我在谷歌上搜了一下,没有找到任何好的讨论,所以我想在这里发帖。
然而,在Eric Lippert博客上的一篇文章的评论中,他给出了一个实现嵌套接口的类的示例,以及一个实现具有嵌套类作为类型参数的泛型接口的类的示例(它无法编译,他称之为当前编译器中的“错误”)。 这两个示例都涉及接口,因此我想知道是否有一些关于嵌套类的特殊规则。 看来确实有。
我能够避免这个问题(至少在接口方面)通过继承一个包含嵌套接口的单独类。(在我的情况下,我也返回对这些接口的引用。)
与其:
public class MyClass<T1, T2, T3> :
MyClass<T1, T2, T3>.Interface
where T1 : ...
where T2 : ...
where T3 : ... {
public interface Interface { Interface SomeMethod(); }
Interface Interface.SomeMethod() {
...
}
}
// compile error: Circular base class dependency
做类似这样的事情:
public sealed class MyClassInterfaces<T1, T2, T3>
where T1 : ...
where T2 : ...
where T3 : ... {
public interface Interface { Interface SomeMethod(); }
}
sealed class MyClass<T1, T2, T3> :
MyClassInterfaces<T1, T2, T3>.Interface
where T1 : ...
where T2 : ...
where T3 : ... {
MyClassInterfaces<T1, T2, T3>.Interface
MyClassInterfaces<T1, T2, T3>.Interface.SomeMethod() {
...
}
}
public abstract class MyClassInterfaces<T1, T2, T3>
where T1 : ...
where T2 : ...
where T3 : ... {
public interface Interface { Interface SomeMethod(); }
}
sealed class MyClass<T1, T2, T3> :
MyClassInterfaces<T1, T2, T3>,
MyClassInterfaces<T1, T2, T3>.Interface
where T1 : ...
where T2 : ...
where T3 : ... {
Interface Interface.SomeMethod() {
...
}
}
我认为嵌套的含义是表示嵌套类型是嵌套类型定义的一部分。以这种解释方式,限制是有意义的,因为当编译器访问 A 的定义时,A.B 尚未定义,即使在 A 结束时,它也已经在 A.B 的基础上定义。
这对我来说毫无意义...你试图扩展不存在的东西!!! B类仅存在于A类的范围内,因此我认为存在某种继承关系。