问题描述
有人可以向我解释为什么以下代码会输出它的作用吗?
为什么T a String在第一个,而不是Int32,为什么在下一个输出中是相反的情况?
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?
这个谜题来自于
当我浏览代码时,我真的不知道它是Int32还是字符串:
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();
}
}
推荐答案
更改代码略有:
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
}
}
注意我是如何改变的code> C 的基类从 B
到 A< T> .B
。这会将 System.Int32
的输出更改为 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
.
没有它, A< string> .BC
不是来自 A< string> .B
,但是来自 A< int> .B
,导致您看到的行为。这是因为通常,基类中定义的名称可通过非限定查找获得,名称 B
在基类 A< int> 。
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>
.
这篇关于继承和泛型类型设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!