【发布时间】:2008-10-16 15:53:42
【问题描述】:
我想做这样的事情:
myYear = record.GetValueOrNull<int?>("myYear"),
注意可空类型作为泛型参数。
由于 GetValueOrNull 函数可以返回 null,我的第一次尝试是这样的:
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : class
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
{
return (T)columnValue;
}
return null;
}
但我现在得到的错误是:
类型“int?”必须是引用类型才能将其用作泛型类型或方法中的参数“T”
对! Nullable<int> 是 struct!所以我尝试将类约束更改为struct 约束(并且作为副作用不能再返回null):
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct
现在分配:
myYear = record.GetValueOrNull<int?>("myYear");
给出以下错误:
类型“int?”必须是不可为空的值类型才能将其用作泛型类型或方法中的参数“T”
是否尽可能将可空类型指定为泛型参数?
【问题讨论】:
-
请在
DbDataRecord签名IDataRecord..