我正在使用反射机制检索泛型类对象的属性,通过检测它们的数据类型(例如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", 有没有办法检测到后面的组合数据类型?