【问题标题】:How to detect data type combined with nullable property如何检测与可为空属性结合的数据类型
【发布时间】:2019-12-16 18:41:25
【问题描述】:

我正在使用反射来检索通用类对象属性,通过检测它们的数据类型(例如 System.String、System.DateTime 等)并根据数据类型转换值,例如:

switch (prop.PropertyType.FullName)
{
    case "System.String":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
    case "System.Int32":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            -1 : Convert.ToInt32(_propertyDataValue));
        break;
    case "System.DateTime":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            DateTime.MinValue : Convert.ToDateTime(_propertyDataValue));
        break;
    case "System.Double":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            0 : Convert.ToDouble(_propertyDataValue));
        break;
    case "System.Boolean":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            false : Convert.ToBoolean(_propertyDataValue));
        break;
    default:
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
}

然而,当我遇到定义为int?的属性时,double?还是 DateTime? 这将是 Nullable 类型,我无法确定该属性的确切数据类型,他的反射只给了我“System.Nullable”的类型,是否存在无论如何要检测背后的组合数据类型?

【问题讨论】:

标签: c# .net reflection nullable


【解决方案1】:

正如评论部分提到的@madreflection。您需要使用Nullable.GetUnderlyingType,如下所示:

var propType = prop.PropertyType;

if (Nullable.GetUnderlyingType(propType) != null)
{
    // It's nullable
    propType = Nullable.GetUnderlyingType(propType);
}

switch (propType.FullName)
{
    case "System.String":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
    case "System.Int32":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            -1 : Convert.ToInt32(_propertyDataValue));
        break;
    case "System.DateTime":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            DateTime.MinValue : Convert.ToDateTime(_propertyDataValue));
        break;
    case "System.Double":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            0 : Convert.ToDouble(_propertyDataValue));
        break;
    case "System.Boolean":
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            false : Convert.ToBoolean(_propertyDataValue));
        break;
    default:
        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
            string.Empty : Convert.ToString(_propertyDataValue));
        break;
}

【讨论】:

    猜你喜欢
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多