【发布时间】:2017-09-08 22:31:22
【问题描述】:
Nullable 类是如何做到的?
public class Foo<T>
{
public T Bar { get; set; }
}
var n1 = new Nullable<int>(123).GetType().Name; // "Int32"
var n2 = new Foo<int>().GetType().Name; // "Foo`1"
是否可以使Foo 具有相同的类型名称,即“Int32”?
【问题讨论】:
-
请注意,
Nullable在运行时得到了一些非常特殊的处理。特别是,如果没有值的Nullable被装箱,则装箱的对象是null- 与所有其他值类型相反。我怀疑这是类似的特殊待遇。 -
另见How is ValueType.GetType() able to determine the type of the struct?。因为
Nullable<T>是ValueType并且值类型是装箱的,所以这就是你得到的(另见Nullable.cs 源代码) -
答案是我的评论和@AdrianoRepetti 的结合。我会起草一个答案。
标签: c#