【发布时间】:2010-01-20 12:11:59
【问题描述】:
我必须遍历几个类中的所有属性并检查任何可为空的属性以查看它们是否具有值。如何将 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
}
}
【问题讨论】:
-
你不能只做 if(propInfo.GetValue(this, null) != null) 吗?还是要显式使用 HasValue?
标签: c# generics reflection nullable