我今天在工作中查看代码库中的其他内容时遇到了以下代码,我什至不知道这样的事情是如何工作的。 有人可以向我解释这怎么可能吗?
class Outer {
void MethodOne(); // Non-virtual
// more non-virtual methods
public class InnerFoo : Outer { // HOW is this possible?
void InnerMethodOne();
// more methods on the derived class
}
public class InnerBar : Outer { // o_O
// stuff
}
}
我不知道编译器如何解析它,更不用说解释这样的类结构了。
从编译器的角度来看,这是相当简单的。编译器为继承自
Outer
的两个类输出 MSIL。任何尝试在 InnerBar
命名空间之外引用 InnerFoo
或 Outer
的代码都会导致编译错误。
就输出字节码而言,此代码与以下代码相同
class Outer {
void MethodOne();
// more non-virtual methods
}
class InnerFoo : Outer {
void InnerMethodOne();
// more methods on the derived class
}
class InnerBar : Outer {
// stuff
}
要记住的相关一点是,对于编译器来说,类只是一个类,无论是否嵌套。嵌套类和普通类之间的唯一区别是编译器如何允许其他类引用它。