【问题标题】:Reflection - check all nullable properties have values反射 - 检查所有可为空的属性是否有值
【发布时间】: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


【解决方案1】:

请注意,我假设您的意思是 Nullable&lt;T&gt;;如果您的意思是 Nullable&lt;T&gt; 或参考,那么您已经拥有它:object(来自 GetValue) - 只需检查 null

Nullable&lt;T&gt;的情况下;您不能转换为单个非泛型类型(object 除外)-但您不需要;只需检查它不是null,因为空的Nullable&lt;T&gt; 被装箱到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&lt;T&gt; 结构完全分开;所以你根本不会投到Nullable。碰巧的是,Nullable 的存在是为了提供诸如 GetUnderlyingType 之类的东西来帮助您使用 Nullable&lt;T&gt;

【讨论】:

  • 你在第一句话中有两次Nullable&lt;T&gt;...这种说法没有意义...你的意思是说Nullable & Nullable&lt;T&gt;
  • @t3chb0t 我的意思是写的;可空值有两种截然不同的含义,我要澄清的是,对于其中一个来说,它自动是微不足道的,实际上它们都可以(通过特殊的装箱规则)以相同的方式处理 - 并且:进一步:方式OP 正在尝试执行此操作(这涉及使用更通用的 Nullable-T 版本)不存在且不存在。
【解决方案2】:

由于您已确定该属性的类型为 Nullable&lt;something&gt;,您知道 其值 具有 HasValue 属性 - 因此通过反射找到该属性并获取其值。

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2015-01-11
    相关资源
    最近更新 更多