埃里克·利珀特(Eric Lippert)访谈中的一个难题:继承和通用类型设置 [英] Puzzle from an Interview with Eric Lippert: Inheritance and Generic Type Setting
问题描述
有人可以向我解释以下代码为何输出其功能吗? 为什么T在第一个字符串中是String而不是Int32,为什么在下一个输出中是相反的情况?
这个难题来自对埃里克·利珀特的采访 >
浏览代码时,我真的不知道它是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();
}
}
略微更改代码:
public class A<T>
{
public class B : A<int>
{
public void M() { System.Console.WriteLine(typeof(T)); }
public class C : A<T>.B { }
}
}
public class P
{
public static void Main()
{
(new A<string>.B.C()).M(); //Outputs System.String
}
}
请注意如何将C
的基类从B
更改为A<T>.B
.这会将输出从System.Int32
更改为System.String
.
否则,A<string>.B.C
不是从A<string>.B
派生的,而是从A<int>.B
派生的,从而导致您看到的行为.这是因为一般而言,基类中定义的名称可以通过不限定条件的查找获得,而名称B
是在基类A<int>
中定义的.
Can someone explain to me why the below code outputs what it does? Why is T a String in the first one, not an Int32, and why is it the opposite case in the next output?
This puzzle is from an interview with Eric Lippert
When I look through the code, I really have no idea if it's going to be an Int32 or a 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();
}
}
Changing the code slightly:
public class A<T>
{
public class B : A<int>
{
public void M() { System.Console.WriteLine(typeof(T)); }
public class C : A<T>.B { }
}
}
public class P
{
public static void Main()
{
(new A<string>.B.C()).M(); //Outputs System.String
}
}
Note how I changed C
's base class from B
to A<T>.B
. This changes the output from System.Int32
to System.String
.
Without that, A<string>.B.C
derives not from A<string>.B
, but from A<int>.B
, causing the behaviour you've seen. That's because in general, names defined in base classes are available by unqualified lookup, and the name B
is defined in the base class A<int>
.
这篇关于埃里克·利珀特(Eric Lippert)访谈中的一个难题:继承和通用类型设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!