我必须遍历几个类中的所有属性并检查任何可为 null 的属性以查看它们是否具有值。如何将从 propertyInfo.GetValue() 返回的值转换为通用可为 null 的类型,以便检查 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
}
}
最佳答案
请注意,我假设您的意思是 Nullable<T>
;如果你的意思是Nullable<T>
或引用资料,那么您已经拥有它:object
(来自 GetValue
) - 只需检查 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>)
}
}
为了澄清,Nullable
是一个静态实用程序类,它完全独立到Nullable<T>
结构;所以你不要转换为 Nullable
根本。碰巧,Nullable
存在是为了提供类似 GetUnderlyingType
的东西这有助于您使用 Nullable<T>
.
关于c# - 反射 - 检查所有可为空的属性是否有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2101185/