不幸的是,您将无法通过使用泛型获得 Nullable 返回类型和对引用类型的支持,除非您在调用时指定希望返回 Nullable
public static T Get<T>(this DataRow row, string field)
{
if (row.IsNull(field))
return default(T);
else
return (T)row[field];
}
当你打电话时
var id = dr.Get<int?>("user_id");
我没有测试这个,只是把它扔在这里。试一试。
编辑:
或者,如果您真的想将值类型转换为可空值并且仍然能够支持引用类型,那么这样的事情可能会起作用
public static object GetDr<T>(this DataRow row, string field)
{
// might want to throw some type checking to make
// sure row[field] is the same type as T
if (typeof(T).IsValueType)
{
Type nullableType = typeof(Nullable<>).MakeGenericType(typeof(T));
if (row.IsNull(field))
return Activator.CreateInstance(nullableType);
else
return Activator.CreateInstance(nullableType, new[] { row[field] });
}
else
{
return row[field];
}
}
但是,它需要对每次使用进行强制转换
var id = dr.Get<string>("username") as string;
var id = (int?)dr.Get<int>("user_id");
然而,这不会像在泛型类型参数中接受可空类型那样有效。