プロシージャによって返されるデータベース値を処理するための変換メソッドを作成しました。次のようになります。
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
この状況を処理するためにこのメソッドを改善するにはどうすればよいですか? メソッドのユーザーがこの種の問題を気にせず、ダブルキャストする必要がないことを望みます。これは可能ですか?