You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PropertyInfo.PropertyType判断属性是否为可空bool类型?

检测可空bool属性并设置默认值的方案

问题背景

为自动生成的类批量设置默认属性值,编写了SetDefaults扩展方法,但无法识别bool?(可空布尔)类型的属性——这类属性的PropertyType不等于typeof(bool),导致无法将其默认值设为false。现有方法框架如下:

public static T SetDefaults<T>(this T model) where T : IModelClasses
{
    foreach (PropertyInfo prop in model.GetType().GetProperties())
    {
        if (prop.PropertyType == typeof(string)) prop.SetValue(model, string.Empty, null);
        else if (prop.PropertyType == typeof(bool)) prop.SetValue(model, false, null); // 无法处理bool?类型
        // 其他类型处理逻辑
    }
    return model;
}

曾尝试通过需要实例对象的GetType<T>方法获取基础类型,但该方法无法直接通过PropertyType实现检测需求。


解决方案

可空值类型(如bool?)本质是Nullable<T>泛型结构体,可通过以下两种方式识别bool?类型:

1. 直接匹配可空bool类型

直接判断属性类型是否等于typeof(bool?),精准定位目标类型:

public static T SetDefaults<T>(this T model) where T : IModelClasses
{
    foreach (PropertyInfo prop in model.GetType().GetProperties())
    {
        if (prop.PropertyType == typeof(string))
        {
            prop.SetValue(model, string.Empty);
        }
        // 处理非可空bool
        else if (prop.PropertyType == typeof(bool))
        {
            prop.SetValue(model, false);
        }
        // 处理可空bool(bool?)
        else if (prop.PropertyType == typeof(bool?))
        {
            prop.SetValue(model, false);
        }
        // 其他类型处理逻辑
    }
    return model;
}

2. 通用可空类型检测(适用于所有可空值类型)

使用Nullable.GetUnderlyingType方法获取可空类型的基础类型,若基础类型为bool,则判定为bool?类型:

public static T SetDefaults<T>(this T model) where T : IModelClasses
{
    foreach (PropertyInfo prop in model.GetType().GetProperties())
    {
        if (prop.PropertyType == typeof(string))
        {
            prop.SetValue(model, string.Empty);
        }
        else
        {
            // 获取可空类型的基础类型,非可空类型返回null
            var underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);
            // 同时处理非可空bool和可空bool
            if (prop.PropertyType == typeof(bool) || (underlyingType != null && underlyingType == typeof(bool)))
            {
                prop.SetValue(model, false);
            }
        }
        // 其他类型处理逻辑
    }
    return model;
}

说明

  • Nullable.GetUnderlyingType方法专门用于提取可空值类型的基础类型,无需依赖实例对象,完全通过PropertyInfo的类型信息即可实现检测。
  • 若需要为其他可空值类型(如int?、DateTime?)设置默认值,可复用第二种方案的逻辑,只需修改基础类型的判断条件。

内容的提问来源于stack exchange,提问作者E. A. Bagby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 10:45:33