检查正确的方法,如果一个类型是可空 [英] Correct way to check if a type is Nullable
本文介绍了检查正确的方法,如果一个类型是可空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了检查是否键入
(属性类型
)是空的,我使用的:
In order to check if a Type
( propertyType
) is nullable, I'm using:
bool isNullable = "Nullable`1".Equals(propertyType.Name)
是否有某种方式,避免使用魔法字符串?
Is there some way that avoid using magic strings ?
推荐答案
当然 - 使用 Nullable.GetUnderlyingType
:
Absolutely - use Nullable.GetUnderlyingType
:
if (Nullable.GetUnderlyingType(propertyType) != null)
{
// It's nullable
}
请注意,这里使用的非泛型静态类的 System.Nullable
,而不是一般的结构可空< T>
Note that this uses the non-generic static class System.Nullable
rather than the generic struct Nullable<T>
.
另外请注意,将检查其是否表示的具体的(闭)空值类型...如果你把它用在一个的通用的类型将无法正常工作,如:
Also note that that will check whether it represents a specific (closed) nullable value type... it won't work if you use it on a generic type, e.g.
public class Foo<T> where T : struct
{
public Nullable<T> Bar { get; set; }
}
Type propertyType = typeof(Foo<>).GetProperty("Bar").PropertyType;
// propertyType is an *open* type...
这篇关于检查正确的方法,如果一个类型是可空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文