[英]How to detect data type combined with nullable property
我使用反射来检索泛型类对象属性,通过检测它们的数据类型(例如 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? 或日期时间? 这将是一个 Nullable 类型,我无法确定该属性的确切数据类型,反射只给我类型为 "System.Nullable" ,无论如何检测后面的组合数据类型?
正如@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.