为什么下面的代码输出 System.Int32 而不是 System.String?

Yac*_*sad 8 c# type-systems

为什么下面的代码输出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(); }
}
Run Code Online (Sandbox Code Playgroud)

我得到了这个代码表:https : //www.dotnetcurry.com/csharp/1292/eric-lippert-interview

小智 0

为什么System.Int32在删除时返回此代码.C()使其返回System.String有点没有意义。

不过,有一个解释。即使public class C : B { }没有真正做任何事情,它仍然会说“嘿,因为我们继承自 B,那么我们必须给出一个 int!”。如果我们删除.C(),那么我们将从 A 继承,它基本上接受任何类型的参数,在我们的情况下,是一个字符串。

因此,我想说,因为我们一路“进入”C,所以我们确保告诉编译器我们正在使用 int,因此我们从运行这段代码得到的结果!