反射 - 检查所有可空属性是否具有值

时间:2010-01-20 12:12:00

标签: c# generics reflection nullable

我必须遍历几个类中的所有属性并检查任何可空属性以查看它们是否具有值。如何将propertyInfo.GetValue()返回的值转换为通用的可空类型,以便我可以检查HasValue属性?

代码剪裁简洁:

foreach (PropertyInfo propInfo in this.GetType().GetProperties())
{
    if (<Snip: Check to see that this is a nullable type>)                                                                      
    {
           //How do i cast this properly in here to allow me to do:
           if(!((Nullable)propInfo.GetValue(this, null)).HasValue)
                  //More code here
    }
}

2 个答案:

答案 0 :(得分:31)

注意我假设你的意思是Nullable<T>;如果您的意思是Nullable<T>或引用,那么您已经拥有它:object(来自GetValue) - 只需检查null

Nullable<T>的情况下;你不能转换为单一的非泛型类型(object除外) - 但你不需要;只需检查它不是null,因为空Nullable<T>被装箱到null,而GetValue会返回object(因此它会将值框住)。< / p>

if(Nullable.GetUnderlyingType(propInfo.PropertyType) != null) {
    // it is a Nullable<T> for some T
    if(propInfo.GetValue(this, null) != null) {
        // it has a value (it isn't an empty Nullable<T>)
    }
}

为了澄清,Nullable是一个静态实用程序类,它与<{1}}结构完全分离;所以你根本不要施展到Nullable<T>。碰巧的是,Nullable存在提供Nullable之类的内容,可帮助您使用GetUnderlyingType

答案 1 :(得分:0)

由于您已确定属性属于Nullable<something>类型,因此您知道其值具有HasValue属性 - 因此通过反射找到该属性并获取其值