【发布时间】:2020-06-21 17:35:41
【问题描述】:
为什么下面的代码输出的是System.Int32而不是System.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.C()).M(); }
}
我得到了这个代码表:https://www.dotnetcurry.com/csharp/1292/eric-lippert-interview
【问题讨论】:
-
简短的回答是因为
B继承自A<int>。 -
你为什么希望它打印 System.String?
-
@RobertHarvey,长答案是什么?请考虑
(new A<string>.B()).M();输出System.String,而不是System.Int32。 -
@Steve,因为据我所知,A
.B 的 T 等于 String。
标签: c# type-systems