Eric Lippert 所说的 "you need to know what the base class is to determine what the base class is" 是什么意思?

What does Eric Lippert mean by "you need to know what the base class is to determine what the base class is"?

我刚刚读了 Eric Lippert 的这篇有趣的文章,Top 10 Worst C# Features。在接近尾声时他说:

The rules for resolving names after the aforementioned colon are not well founded; you can end up in situations where you need to know what the base class is in order to determine what the base class is.

冒号指的是继承运算符(例如 Dog : Animal)。

Eric指的是什么情况?谁能提供代码示例?

这可能发生在具有泛型、继承和嵌套的复杂场景中 classes:

class Base<T> {
    public class Inner {}
}

class Derived : Base<Derived.Inner2> {
    public class Inner2 : Inner {}
}

Result

  • 要确定Derived的基础class,我们需要绑定Derived.Inner2
  • 要绑定 Derived.Inner2,我们需要解析 Inner 符号。
  • Inner符号继承自其包含范围的基class,因此我们需要再次确定Derived的基class。

SLaks给出了很好的答案;请参阅我的评论以获取一些附加说明。

正如我在评论中所说,我正在寻找关于这个主题的旧笔记,如果找到它们,我会写一篇博客。这是一个有趣的附加示例。这个程序是合法的。 class声明中的N和字段声明中的N的含义相同还是不同?如果它们相同,那么它们的完全限定类型表达式是什么?如果它们不同,为什么规范要求它们不同?

public class N {}
public class B<T> 
{
    public class N {}
}

public class D : B<N> // base class
{
  N n;  // field
}

这说明了根本问题:名称查找要求基数 class 已知,但基数 class 是按名称查找的。

现在想想接口如何在混合中工作。假设 class D 也实现了一个接口 IN,同样嵌套在 B 中并且全局可用。接口查找解析为基础 class 还是全局命名空间?这些是您在编写编译器时必须解决的问题。