我已经制定了一种转换方法来处理 procs 返回的数据库值。它看起来像这样:
public static T GetVerifiedValue<T>(this IDataRecord record, int index)
{
object value = record[index];
if (value is string)
value = string.IsNullOrEmpty(value as string) ? null : value;
Type nullableUnderlyingType = Nullable.GetUnderlyingType(typeof(T));
if (nullableUnderlyingType != null)
{
if (nullableUnderlyingType.IsEnum)
return value == null || value.Equals(DBNull.Value) ? default(T) : (T)Enum.ToObject(nullableUnderlyingType, value);
}
/*
//This is my try on solving the problem, but won't compile
//because T has no struct constraint
if (value is ValueType)
{
ValueType structValue = (ValueType)value;
return value.Equals(DBNull.Value) ? default(T) : (T)structValue;
}
*/
return value == null || value.Equals(DBNull.Value) ? default(T) : (T)value;
}
问题是当数据库返回一个整数时,value
变量将包含一个int
,当T
是一个时short
,我得到一个InvalidCastException
。
我该如何改进这种方法来处理这种情况?我希望该方法的用户不必担心这种问题,而不必双重施法。这可能吗?