如何检测具有可空属性的数据类型

3

我正在使用反射机制检索泛型类对象的属性,通过检测它们的数据类型(例如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? 这些可空类型时,我无法确定该属性的确切数据类型。 只有反射返回类型 "System.Nullable", 有没有办法检测到后面的组合数据类型?


太棒了,谢谢! - Kev D.
1个回答

2
如评论区中@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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接