我想做这样的事情:
myYear = record.GetValueOrNull<int?>("myYear"),
Run Code Online (Sandbox Code Playgroud)
请注意可空类型作为通用参数.
由于该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;
}
Run Code Online (Sandbox Code Playgroud)
但我现在得到的错误是:
类型'int?' 必须是引用类型才能在泛型类型或方法中将其用作参数"T"
对!Nullable<int>是一个struct!所以我尝试将类约束更改为struct约束(并且副作用不能再返回null):
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct
Run Code Online (Sandbox Code Playgroud)
现在任务:
myYear = record.GetValueOrNull<int?>("myYear");
Run Code Online (Sandbox Code Playgroud)
给出以下错误:
类型'int?' 必须是非可空值类型才能在泛型类型或方法中将其用作参数"T"
是否可以将可空类型指定为通用参数?