我必须遍历几个类中的所有属性并检查任何可空属性以查看它们是否具有值。如何将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
}
}
答案 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
属性 - 因此通过反射找到该属性并获取其值