如何:标识可以为 null 的类型(C# 编程指南)

可以使用 C# typeof 运算符来创建表示可以为 null 的类型的 Type 对象:

System.Type type = typeof(int?);

还可以使用 System.Reflection 命名空间的类和方法来生成表示可以为 null 的类型的 Type 对象。 但是,如果您尝试使用 GetType 方法或 is 运算符在运行时获得可以为 null 的类型变量的类型信息,得到的结果是表示基础类型而不是可以为 null 的类型本身的 Type 对象。

如果对可以为 null 的类型调用 GetType,则在该类型被隐式转换为 Object 时将执行装箱操作。 因此,GetType 总是返回表示基础类型而不是可以为 null 的类型的 Type 对象。

  int? i = 5;
  Type t = i.GetType();
  Console.WriteLine(t.FullName); //"System.Int32"

C# 的 is 运算符还可以作用于可以为 null 的的基础类型。 因此,不能使用 is 来确定变量是否为可以为 null 的类型。 下面的示例演示 is 运算符将 Nullable<int> 变量视为 int 变量。

  static void Main(string[] args)
  {
    int? i = 5;
    if (i is int) // true
      //…
  }

示例

使用下面的代码来确定 Type 对象是否表示可以为 null 的类型。 请记住,如果 Type 对象是通过调用 GetType 返回的,则此代码始终返回 false,如本主题中先前所述。

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}

请参见

参考

可以为 null 的类型(C# 编程指南)

装箱可以为 null 的类型(C# 编程指南)