有人可以向我解释为什么下面的代码会输出它的作用吗? 为什么第一个输出中的 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 : B
中 B
的含义。考虑一个没有泛型的版本:(为简洁起见,我将省略 publics。)
class D { class E {} }
class J {
class E {}
class K : D {
E e; // Fully qualify this type
}
}
可以是 J.E
或 D.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()
写成 string
而 A_of_string.B.C.M()
写成 int
.
关于c# - 来自 Eric Lippert 采访的谜题 : Inheritance and Generic Type Setting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319962/