C#如何检查对象是否可为空

时间:2017-01-02 11:50:23

标签: c#

我在堆栈溢出中看到了一个问题和答案

How to check if an object is nullable?

我无法在上面发表评论,因为我没有超过50条评论,这就是我在这里提问的原因。

if(Nullable.GetUnderlyingType(myType) !=null)
{
   // It's Nullable
}

如果myType是system.string

Nullable.GetUnderlyingType(myType) 

返回null

我认为System.string是无效的!

5 个答案:

答案 0 :(得分:3)

Nullable<T> - 是一种特殊结构,因此System.string不是Nullable<T>System.string是一个类。所有类都可以为null。 所以,

if (myType.IsClass)
{
    //can be null
}

答案 1 :(得分:2)

致电Nullable.GetUnderlyingType()不会为typeof(string)返回任何有意义的内容。 documentation提及:

  

返回指定可空类型的基础类型参数。

     

返回值

     

nullableType参数的类型参数,如果nullableType参数是封闭的通用可空类型;否则,null。

换句话说,如果您实际传递了一个实现Nullable<T>的类型,例如int?bool?等,它只返回一些有用的东西。 就是“可空类型”的含义。

您还可以在Marc's answer to the question you link to的代码中看到其预期用途:

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

答案 2 :(得分:1)

所有引用类型都可以设置为null,但不是Nullable<T>类型,您可以使用!myType.IsValueType

检查类型是否为引用类型

答案 3 :(得分:1)

System.String(或字符串)是引用类型。这意味着,此类型的实例可以是bool。 Nullables是一种向值类型添加此功能的方法(如基本类型int#obj1{ float:right; width: 96px; height: 100px; -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */ animation: mymove 20s infinite; animation-delay:2s; background-image:url("obj1.png"); transform: scale(1.5); -moz-transform: scale(1.5); -webkit-transform: scale(1.5); -o-transform: scale(1.5); -ms-transform: scale(1.5); /* IE 9 */ margin-bottom: 70px; } #obj2{ float:right; width: 96px; height: 100px; -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */ animation: mymove 20s infinite; animation-delay:2s; background-image:url("obj2.png"); transform: scale(1.5); -moz-transform: scale(1.5); -webkit-transform: scale(1.5); -o-transform: scale(1.5); -ms-transform: scale(1.5); /* IE 9 */ margin-bottom: 70px; } #obj6{ float:right; width: 96px; height: 100px; -webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */ animation: mymove 20s infinite; animation-delay:2s; background-image:url("obj6.png"); transform: scale(1.5); -moz-transform: scale(1.5); -webkit-transform: scale(1.5); -o-transform: scale(1.5); -ms-transform: scale(1.5); /* IE 9 */ margin-bottom: 70px; } /* Standard syntax */ @keyframes mymove { 50% {transform: rotate(30deg); } 等。)。

答案 4 :(得分:1)

Nullable是一种类型,而不是类型的属性。 System.String可以为空,但它不是Nullable,与int?不同,Nullable<System.Int32>Nullable的快捷方式。 C#中的所有引用类型都是可空的(您可以传递空引用),而null类型只能接受不可为空的值类型作为参数。

如果要检查给定类型是否可以接受bool CanBeNull<T>() { return default(T) == null; } 作为值,可以执行以下操作:

Nullable

当然,这已经假设默认值是空值,但不一定是这种情况;但它适用于引用类型和int? someValue = null;值类型。如果必须处理接受null但不作为默认值的值类型,则必须专门添加它。除了实际尝试分配空值之外,没有一种确定且简单的方法可以检查给定类型是否可以为null。

实际上,“可以赋值为null”的含义在很大程度上取决于编译器。例如,执行int?之类的操作实际上会调用int? someValue = new int?();的构造函数 - 它等同于if (!type.IsValueType) // Can be assigned null

如果在编译时不知道类型(因此不能使用泛型),可以添加检查给定类型是否为值类型:

null

确保正确处理类,值类型和接口。当然,只是能够为本地/字段分配{{1}}值并不意味着它必然是有效值。最后,决定权归你所有。