c# - 来自 Eric Lippert 采访的谜题 : Inheritance and Generic Type Setting

标签 c# generics inheritance

有人可以向我解释为什么下面的代码会输出它的作用吗? 为什么第一个输出中的 T 是 String 而不是 Int32,为什么在下一个输出中是相反的情况?

这个拼图来自 interview with Eric Lippert

当我查看代码时,我真的不知道它是 Int32 还是 String:

public class A<T>
    {
        public class B : A<int>
        {
            public void M() { System.Console.WriteLine(typeof(T)); }
            public class C : B { }
        }
    }

    public class P
    {
        public static void Main()
        {            
            (new A<string>.B()).M(); //Outputs System.String
            (new A<string>.B.C()).M(); //Outputs System.Int32
            Console.Read();
        }
    }

最佳答案

Can someone explain to me why the below code outputs what it does?

我会在这里简单地解释一下;可以找到更长的解释 here .

问题的症结在于确定 class C : BB 的含义。考虑一个没有泛型的版本:(为简洁起见,我将省略 publics。)

class D { class E {} }
class J {
  class E {}
  class K : D {
    E e; // Fully qualify this type
  }
}

可以是 J.ED.E;是哪一个? C# 中解析名称时的规则是查看基类层次结构,只有在失败时才查看您的容器。 K已经继承了一个成员E,所以它不需要查看它的容器就可以发现它的容器有一个包含成员E。

但我们看到拼图具有相同的结构;它只是被泛型混淆了。我们可以将泛型视为模板,并将 A-of-string 和 A-of-int 的构造写为类:

class A_of_int 
{
  class B : A_of_int
  {
    void M() { Write("int"); }
    class C : B { } // A_of_int.B
  }
}
class A_of_string
{
  class B : A_of_int
  {
    void M() { Write("string"); }
    class C : B {} // still A_of_int.B
  }
}

现在应该清楚为什么 A_of_string.B.M() 写成 stringA_of_string.B.C.M() 写成 int.

关于c# - 来自 Eric Lippert 采访的谜题 : Inheritance and Generic Type Setting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319962/

相关文章:

python - __init__() 缺少 1 个必需的位置参数 : 'quantity'

c# - 如何让 File.OpenText 返回不可为空的 StreamReader

c# - 如何对MainWindow使用UserControl事件

c# - 将值 [0.0-1.0] 映射到颜色增益

swift - 我如何扩展其值就是字典本身的字典?

c# - 显示 C# 1 数据类型的通用等效项的表格

c# - Webbrowser 控件在放置在 Outlook 加载项中时不接收 Tab/Delete/Back 键

c# - 在 C# 中,如何在方法中实例化传递的泛型类型?

java - Java 中设置子类所需常量的最佳实践是什么?

c++ - 我有这两个相似的类(class)。您将使用什么设计来分解代码?