如何检查对象是否可以为空?

时间:2008-12-17 14:17:16

标签: c# .net nullable

如何检查给定对象是否可为空,换句话说,如何实现以下方法......

bool IsNullableValueType(object o)
{
    ...
}

编辑:我正在寻找可以为空的值类型。我没有记住ref类型。

//Note: This is just a sample. The code has been simplified 
//to fit in a post.

public class BoolContainer
{
    bool? myBool = true;
}

var bc = new BoolContainer();

const BindingFlags bindingFlags = BindingFlags.Public
                        | BindingFlags.NonPublic
                        | BindingFlags.Instance
                        ;


object obj;
object o = (object)bc;

foreach (var fieldInfo in o.GetType().GetFields(bindingFlags))
{
    obj = (object)fieldInfo.GetValue(o);
}

obj现在指的是boolSystem.Boolean)类型的对象,其值等于true。我真正想要的是Nullable<bool>

类型的对象

所以现在作为一个解决方法我决定检查o是否可以为空并在obj周围创建一个可以为空的包装器。

14 个答案:

答案 0 :(得分:248)

有两种类型的可空 - Nullable<T>和引用类型。

Jon已经纠正我,如果盒装了很难获得类型,但你可以使用泛型:   - 那下面怎么样。这实际上是测试类型T,但是使用obj参数纯粹用于泛型类型推断(以便于调用) - 但它在没有obj参数的情况下几乎完全相同。

static bool IsNullable<T>(T obj)
{
    if (obj == null) return true; // obvious
    Type type = typeof(T);
    if (!type.IsValueType) return true; // ref-type
    if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
    return false; // value-type
}

但是,如果您已将值装箱到对象变量,那么这将无法正常工作。

答案 1 :(得分:48)

使用方法重载有一个非常简单的解决方案

http://deanchalk.com/is-it-nullable/

摘录:

public static class ValueTypeHelper
{
    public static bool IsNullable<T>(T t) { return false; }
    public static bool IsNullable<T>(T? t) where T : struct { return true; }
}

然后

static void Main(string[] args)
{
    int a = 123;
    int? b = null;
    object c = new object();
    object d = null;
    int? e = 456;
    var f = (int?)789;
    bool result1 = ValueTypeHelper.IsNullable(a); // false
    bool result2 = ValueTypeHelper.IsNullable(b); // true
    bool result3 = ValueTypeHelper.IsNullable(c); // false
    bool result4 = ValueTypeHelper.IsNullable(d); // false
    bool result5 = ValueTypeHelper.IsNullable(e); // true
    bool result6 = ValueTypeHelper.IsNullable(f); // true

答案 2 :(得分:30)

“如何检查类型是否可以为空”的问题?实际上是“如何检查类型是否为Nullable<>?”,可以推广为“如何检查类型是否是某种泛型类型的构造类型?”,这样它不仅可以回答“ Nullable<int>Nullable<>?“,还有”List<int>List<>吗?“。

大多数提供的解决方案都使用Nullable.GetUnderlyingType()方法,这显然只适用于Nullable<>的情况。我没有看到适用于任何通用类型的一般反射解决方案,因此我决定将其添加到后代,即使这个问题很久以前就已经得到了回答。

要使用反射检查某个类型是否为某种形式的Nullable<>,您首先必须将构造的泛型类型(例如Nullable<int>)转换为泛型类型定义Nullable<>。您可以使用GetGenericTypeDefinition()类的Type方法执行此操作。然后,您可以将结果类型与Nullable<>进行比较:

Type typeToTest = typeof(Nullable<int>);
bool isNullable = typeToTest.GetGenericTypeDefinition() == typeof(Nullable<>);
// isNullable == true

同样可以应用于任何泛型类型:

Type typeToTest = typeof(List<int>);
bool isList = typeToTest.GetGenericTypeDefinition() == typeof(List<>);
// isList == true

有几种类型似乎相同,但不同数量的类型参数意味着它是完全不同的类型。

Type typeToTest = typeof(Action<DateTime, float>);
bool isAction1 = typeToTest.GetGenericTypeDefinition() == typeof(Action<>);
bool isAction2 = typeToTest.GetGenericTypeDefinition() == typeof(Action<,>);
bool isAction3 = typeToTest.GetGenericTypeDefinition() == typeof(Action<,,>);
// isAction1 == false
// isAction2 == true
// isAction3 == false

由于Type对象每种类型都被实例化一次,因此可以检查它们之间的引用相等性。因此,如果要检查两个对象是否具有相同的泛型类型定义,则可以编写:

var listOfInts = new List<int>();
var listOfStrings = new List<string>();

bool areSameGenericType =
    listOfInts.GetType().GetGenericTypeDefinition() ==
    listOfStrings.GetType().GetGenericTypeDefinition();
// areSameGenericType == true

如果您想检查一个对象是否可以为空,而不是Type,那么您可以将上述技术与Marc Gravell的解决方案一起使用来创建一个相当简单的方法:

static bool IsNullable<T>(T obj)
{
    if (!typeof(T).IsGenericType)
        return false;

    return typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
}

答案 3 :(得分:20)

好吧,你可以使用:

return !(o is ValueType);

...但是对象本身不可为空或其他 - 类型。你打算如何使用它?

答案 4 :(得分:20)

这对我有用,看起来很简单:

static bool IsNullable<T>(T obj)
{
    return default(T) == null;
}

答案 5 :(得分:11)

我能想出的最简单的方法是:

public bool IsNullable(object obj)
{
    Type t = obj.GetType();
    return t.IsGenericType 
        && t.GetGenericTypeDefinition() == typeof(Nullable<>);
}

答案 6 :(得分:9)

这里有两个问题:1)测试以查看Type是否可为空; 2)测试一个对象是否代表可以为空的类型。

对于问题1(测试类型),这是我在自己的系统中使用的解决方案:TypeIsNullable-check solution

对于问题2(测试对象),Dean Chalk上面的解决方案适用于值类型,但它不适用于引用类型,因为使用&lt; T&gt; overload总是返回false。由于引用类型本质上是可空的,因此测试引用类型应始终返回true。有关这些语义的解释,请参阅下面的注释[关于“nullability”]。因此,这是我对Dean的方法的修改:

    public static bool IsObjectNullable<T>(T obj)
    {
        // If the parameter-Type is a reference type, or if the parameter is null, then the object is always nullable
        if (!typeof(T).IsValueType || obj == null)
            return true;

        // Since the object passed is a ValueType, and it is not null, it cannot be a nullable object
        return false; 
    }

    public static bool IsObjectNullable<T>(T? obj) where T : struct
    {
        // Always return true, since the object-type passed is guaranteed by the compiler to always be nullable
        return true;
    }

这是我对上述解决方案的客户端测试代码的修改:

    int a = 123;
    int? b = null;
    object c = new object();
    object d = null;
    int? e = 456;
    var f = (int?)789;
    string g = "something";

    bool isnullable = IsObjectNullable(a); // false 
    isnullable = IsObjectNullable(b); // true 
    isnullable = IsObjectNullable(c); // true 
    isnullable = IsObjectNullable(d); // true 
    isnullable = IsObjectNullable(e); // true 
    isnullable = IsObjectNullable(f); // true 
    isnullable = IsObjectNullable(g); // true

我在IsObjectNullable&lt; T&gt;(T t)中修改Dean方法的原因是他的原始方法总是为引用类型返回false。由于像IsObjectNullable这样的方法应该能够处理引用类型值,并且因为所有引用类型本身都是可空的,所以如果传递了引用类型或null,则该方法应该始终返回true。

上述两种方法可以用以下单一方法替换,并实现相同的输出:

    public static bool IsObjectNullable<T>(T obj)
    {
        Type argType = typeof(T);
        if (!argType.IsValueType || obj == null)
            return true;
        return argType.IsGenericType && argType.GetGenericTypeDefinition() == typeof(Nullable<>);
    }

然而,这种最后的单方法方法的问题在于,当Nullable&lt; T&gt;时,性能会受到影响。使用参数。执行该单个方法的最后一行所花费的处理器时间比允许编译器选择先前在IsObjectNullable调用中使用Nullable&lt; T&gt; -type参数时所示的第二方法重载所花费的处理器时间长得多。因此,最佳解决方案是使用此处所示的双方法方法。

CAVEAT:只有在使用原始对象引用或精确副本调用时,此方法才能可靠地工作,如示例所示。但是,如果可空对象被装箱到另一个类型(例如对象等),而不是保留在其原始的Nullable&lt;&gt;中。形式,这种方法不会可靠。如果调用此方法的代码未使用原始的,未装箱的对象引用或精确副本,则无法使用此方法可靠地确定对象的可为空性。

在大多数编码场景中,要确定可空性,必须依赖于测试原始对象的类型,而不是其参考(例如,代码必须能够访问对象的原始类型以确定可为空性)。在这些更常见的情况下,IsTypeNullable(参见链接)是确定可空性的可靠方法。

P.S。 - 关于“可空性”

我应该在一个单独的帖子中重复一个关于可空性的陈述,这个陈述直接适用于正确解决这个问题。也就是说,我认为这里讨论的重点不应该是如何检查一个对象是否是一个通用的Nullable类型,而是一个人是否可以为其类型的对象赋值null。换句话说,我认为我们应该确定一个对象类型是否可以为空,而不是它是否为Nullable。区别在于语义,即确定可空性的实际原因,这通常是最重要的。

在使用类型可能未知的对象直到运行时(Web服务,远程调用,数据库,提要等)的系统中,常见的要求是确定是否可以为对象分配null,或者是否object可能包含null。在非可空类型上执行此类操作可能会产生错误,通常是异常,这在性能和编码要求方面都非常昂贵。为了采取主动避免此类问题的高度优选方法,有必要确定任意类型的对象是否能够包含空值;即,它是否通常是“可空的”。

在一个非常实际和典型的意义上,.NET术语中的可空性并不一定意味着对象的Type是Nullable的一种形式。事实上,在很多情况下,对象具有引用类型,可以包含空值,因此都可以为空;这些都没有Nullable类型。因此,出于实际目的,在大多数情况下,应该针对可空性的一般概念进行测试,而不是Nullable的依赖于实现的概念。因此,我们不应该只关注.NET Nullable类型,而应该在关注可空性的一般实用概念的过程中结合我们对其要求和行为的理解。

答案 7 :(得分:6)

小心,装箱可空类型(例如Nullable<int>或int?)时:

int? nullValue = null;
object boxedNullValue = (object)nullValue;
Debug.Assert(boxedNullValue == null);

int? value = 10;
object boxedValue = (object)value;
Debug.Assert( boxedValue.GetType() == typeof(int))

它成为一个真正的引用类型,所以你失去了它可以为空的事实。

答案 8 :(得分:6)

我提出的最简单的解决方案是实现Microsoft的解决方案(How to: Identify a Nullable Type (C# Programming Guide))作为扩展方法:

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

然后可以这样调用:

bool isNullable = typeof(int).IsNullable();

这也是访问IsNullable()的合理方式,因为它符合IsXxxx()类的所有其他Type方法。

答案 9 :(得分:3)

可能有点偏离主题,但仍然是一些有趣的信息。我发现很多人使用Nullable.GetUnderlyingType() != null来识别类型是否可以为空。这显然有效,但Microsoft建议使用以下type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)(请参阅http://msdn.microsoft.com/en-us/library/ms366789.aspx)。

我从性能方面看了这个。下面的测试结果(一百万次尝试)是当一个类型可以为空时,Microsoft选项可以提供最佳性能。

Nullable.GetUnderlyingType(): 1335ms (慢3倍)

GetGenericTypeDefinition()== typeof(Nullable&lt;&gt;): 500ms

我知道我们谈论的是一小部分时间,但每个人都喜欢调整毫秒:-)!因此,如果你是老板希望你减少几毫秒,那么这就是你的救世主...

/// <summary>Method for testing the performance of several options to determine if a type is     nullable</summary>
[TestMethod]
public void IdentityNullablePerformanceTest()
{
    int attempts = 1000000;

    Type nullableType = typeof(Nullable<int>);

    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    for (int attemptIndex = 0; attemptIndex < attempts; attemptIndex++)
    {
        Assert.IsTrue(Nullable.GetUnderlyingType(nullableType) != null, "Expected to be a nullable"); 
    }

    Console.WriteLine("Nullable.GetUnderlyingType(): {0} ms", stopwatch.ElapsedMilliseconds);

    stopwatch.Restart();

    for (int attemptIndex = 0; attemptIndex < attempts; attemptIndex++)
   {
       Assert.IsTrue(nullableType.IsGenericType && nullableType.GetGenericTypeDefinition() == typeof(Nullable<>), "Expected to be a nullable");
   }

   Console.WriteLine("GetGenericTypeDefinition() == typeof(Nullable<>): {0} ms", stopwatch.ElapsedMilliseconds);
   stopwatch.Stop();
}

答案 10 :(得分:0)

此版本:

  • 缓存结果更快,
  • 不需要不必要的变量,例如Method(T obj)
  • 不复杂:),
  • 只是静态泛型类,有一次计算字段

public static class IsNullable<T>
{
    private static readonly Type type = typeof(T);
    private static readonly bool is_nullable = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
    public static bool Result { get { return is_nullable; } }
}

bool is_nullable = IsNullable<int?>.Result;

答案 11 :(得分:0)

这是我想出来的,因为其他一切似乎都失败了 - 至少在 PLC - 可移植类库 / .NET Core 上使用&gt; = C# 6

解决方案:为任何类型TNullable<T>扩展静态方法,并使用与将要调用基础类型的静态扩展方法相关的事实优先于通用T扩展方法。

T

public static partial class ObjectExtension
{
    public static bool IsNullable<T>(this T self)
    {
        return false;
    }
}

Nullable<T>

public static partial class NullableExtension
{
    public static bool IsNullable<T>(this Nullable<T> self) where T : struct
    {
        return true;
    }
}

使用Reflection和type.IsGenericType ...在我当前的.NET运行时集上不起作用。 MSDN Documentation也没有帮助。

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

部分原因是因为在.NET Core中,Reflection API已经发生了很大的变化。

答案 12 :(得分:0)

我认为使用Microsoft建议的针对IsGenericType的测试的测试对象是好的,但是在GetUnderlyingType的代码中,Microsoft使用了另一项测试,以确保您未传入通用类型定义{ {1}}:

Nullable<>

答案 13 :(得分:-1)

一种简单的方法:

    public static bool IsNullable(this Type type)
    {
        if (type.IsValueType) return Activator.CreateInstance(type) == null;

        return true;
    }

这些是我的单元测试,全部通过

    IsNullable_String_ShouldReturn_True
    IsNullable_Boolean_ShouldReturn_False
    IsNullable_Enum_ShouldReturn_Fasle
    IsNullable_Nullable_ShouldReturn_True
    IsNullable_Class_ShouldReturn_True
    IsNullable_Decimal_ShouldReturn_False
    IsNullable_Byte_ShouldReturn_False
    IsNullable_KeyValuePair_ShouldReturn_False

实际单元测试

    [TestMethod]
    public void IsNullable_String_ShouldReturn_True()
    {
        var typ = typeof(string);
        var result = typ.IsNullable();
        Assert.IsTrue(result);
    }

    [TestMethod]
    public void IsNullable_Boolean_ShouldReturn_False()
    {
        var typ = typeof(bool);
        var result = typ.IsNullable();
        Assert.IsFalse(result);
    }

    [TestMethod]
    public void IsNullable_Enum_ShouldReturn_Fasle()
    {
        var typ = typeof(System.GenericUriParserOptions);
        var result = typ.IsNullable();
        Assert.IsFalse(result);
    }

    [TestMethod]
    public void IsNullable_Nullable_ShouldReturn_True()
    {
        var typ = typeof(Nullable<bool>);
        var result = typ.IsNullable();
        Assert.IsTrue(result);
    }

    [TestMethod]
    public void IsNullable_Class_ShouldReturn_True()
    {
        var typ = typeof(TestPerson);
        var result = typ.IsNullable();
        Assert.IsTrue(result);
    }

    [TestMethod]
    public void IsNullable_Decimal_ShouldReturn_False()
    {
        var typ = typeof(decimal);
        var result = typ.IsNullable();
        Assert.IsFalse(result);
    }

    [TestMethod]
    public void IsNullable_Byte_ShouldReturn_False()
    {
        var typ = typeof(byte);
        var result = typ.IsNullable();
        Assert.IsFalse(result);
    }

    [TestMethod]
    public void IsNullable_KeyValuePair_ShouldReturn_False()
    {
        var typ = typeof(KeyValuePair<string, string>);
        var result = typ.IsNullable();
        Assert.IsFalse(result);
    }