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

Pad*_*ddy 18 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
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 31

请注意我假设你的意思Nullable<T>; 如果你的意思Nullable<T>或参考,那么你已经拥有它:( objectGetValue) - 只需检查null.

Nullable<T>; 的情况下; 你不能转换为单一的非泛型类型(除了object) - 但你不需要; 只检查它不是null,因为空Nullable<T>是盒装null,并GetValue返回object(因此它将值框).

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>)
    }
}
Run Code Online (Sandbox Code Playgroud)

澄清Nullable一下,是一个与struct 完全分离的静态实用程序类Nullable<T>; 所以你根本就没有Nullable.碰巧的是,Nullable存在提供诸如GetUnderlyingType帮助您使用的东西Nullable<T>.