c# - 反射 - 检查所有可为空的属性是否有值

标签 c# generics reflection nullable

我必须遍历几个类中的所有属性并检查任何可为 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/

相关文章:

c# - 无法获取换行符以在 aspx 页面上呈现

java - 结合 MethodHandles.publicLookup() 与 Method.setAccessible(true)

c# - 如何使用反射动态实例化一个类型?

JAVA——原始类型 VS 对象类型

c# - (Unity C#) Texture2D缩放之谜

c# - ffmpeg 在 Windows Mobile 上使用 C#

java - 无需强制转换即可将值添加到 HashMap

swift - 无法使用类型为 'decode' 的参数列表调用 '(Decodable, from: Data)'

c# - 如何处理通用返回 T 的异常

c# - 不应使用哪些键盘快捷键?