【问题标题】:Why does the following code output System.Int32 instead of System.String? [duplicate]为什么下面的代码输出 System.Int32 而不是 System.String? [复制]
【发布时间】: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&lt;int&gt;
  • 你为什么希望它打印 System.String
  • @RobertHarvey,长答案是什么?请考虑(new A&lt;string&gt;.B()).M(); 输出System.String,而不是System.Int32
  • @Steve,因为据我所知,A.B 的 T 等于 String。

标签: c# type-systems


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回答。在我看来,您不确定原因。我想要一些 C# 语言文档支持的答案。
  • 让我详细说明一下:B 内部的方法 M 将打印 A 的 typeof(T),因为 A 是 B 的父类。因此,M 打印 typeof(T) 即这里是一个字符串,因为我们在 P 中给它的类型。如果我们要删除 C,那么 A.B.M 打印最接近的“T”,这里 A.B.M 将打印“string”。现在,让我们考虑 A.B.C,它等价于 A.B.A.B(因为 C 是 A.B)。然后,距离最后最接近的 A 类型是 ,这就是它返回 Int32 的原因。 (docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…)
  • 虽然看似合理,并且是这个难题的常见答案,但这是错误的。详情请见ericlippert.com/2007/07/27/an-inheritance-puzzle-part-one
猜你喜欢
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
  • 2020-03-14
  • 2011-10-19
  • 1970-01-01
相关资源
最近更新 更多