我想要做这样的事情:可为空类型作为通用参数吗?
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;
}
但现在我得到的错误是:
The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method
权! Nullable<int>
是struct
!所以,我想改变类约束至struct
约束(以及它的副作用不能返回null
更多):
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct
现在的分配:
myYear = record.GetValueOrNull<int?>("myYear");
提供了以下错误:
The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
指定一个可为空的类型作为所有可能的泛型参数?
请请让你的签名`IDataRecord`从`DbDataRecord` .. – nawfal 2013-02-07 05:56:58