代码之家  ›  专栏  ›  技术社区  ›  Dan Tao

如何使用反射判断对象的类型是否可以为空?

  •  9
  • Dan Tao  · 技术社区  · 16 年前

    如果我有 Type ,是否有一些简单的方法来说明它使用反射表示可为空的值类型?理想情况下,比以下内容更干净(更正确):

    static bool IsNullable(Type type)
    {
        return type.IsValueType && type.Name.StartsWith("Nullable");
    }
    
    2 回复  |  直到 16 年前
        1
  •  18
  •   thecoop    16 年前
    type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)
    

    你也可能会发现 Nullable.GetUnderlyingType(Type nullableType) 很有用,很容易得到 T 的 typeof(Nullable<T>) 你进去。

        2
  •  7
  •   Ani    16 年前

    尽管@thecop的答案是正确的(根本没有什么 错误的 在将他的代码放入您提供的方法体中时,这里有一些巨大的gotchas。

    Nullable<T> 被运行时视为“特殊”类型,具有一些非常特殊的语义。尤其是当 可以为空<t> 装箱:

    1. 如果 HasValue == true 它的行为就像一个盒子 T 使之成为 下游团队代码无法判断创建的对象是否由装箱A生成 T 或拳击 可以为空<t> . 取消装箱 T 和 可以为空<t> 两者皆有可能。
    2. 如果 HasValue == false ,装箱只返回 null . 取消装箱 T 将投掷、拆箱至 可以为空<t> 会成功的,为此 hasValue==false .

    在任何一种情况下, boxedNullableObject.GetType() 不会显示该对象是由装箱A生成的 Nullable<T>. 我想不出任何其他表现出这种奇怪行为的价值类型。

    例如,考虑:

    // Output: "System.Nullable`1[System.Int32]"
    Console.WriteLine(typeof(int?));
    
    
    object boxedNullableInt32WithValue = new int?(0);
    
    // Output: "System.Int32", NOT "System.Nullable`1[System.Int32]"
    Console.WriteLine(boxedNullableInt32WithValue.GetType()); 
    
    
    object boxedNullableInt32WithoutValue = new int?();
    
    // NullReferenceException is thrown
    Console.WriteLine(boxedNullableInt32WithoutValue.GetType()); 
    

    因此,编写一种方法,如:

    public static bool IsObjectANullableT(this object obj) { ... }

    真是个坏主意。

    编辑 :另一个注意事项是,我刚刚意识到有一个框架方法可以使用与@thecop's sample相同的技术来满足您的需要: Nullable.GetUnderlyingType .

    用途:

    static bool IsNullable(Type type)
    {
        return Nullable.GetUnderlyingType(type) != null;
    }
    

    编辑 :刚才看到,@coop在他的回答中也提到了这一点。我的错误。

    推荐文章