可空类型作为泛型参数可能吗? [英] Nullable type as a generic parameter possible?
问题描述
我想做这样的事情:
myYear = record.GetValueOrNull<int?>("myYear"),
注意可空类型作为泛型参数.
Notice the nullable type as the generic parameter.
由于 GetValueOrNull
函数可能返回 null,我的第一次尝试是这样的:
Since the GetValueOrNull
function could return null my first attempt was this:
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;
}
但我现在得到的错误是:
But the error I'm getting now is:
'int?' 类型必须是引用类型才能将其用作泛型类型或方法中的参数T"
The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method
没错!Nullable
是一个 struct
!所以我尝试将类约束更改为 struct
约束(并且作为副作用不能再返回 null
):
Right! Nullable<int>
is a struct
! So I tried changing the class constraint to a struct
constraint (and as a side effect can't return null
any more):
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct
现在分配:
myYear = record.GetValueOrNull<int?>("myYear");
出现以下错误:
'int?' 类型必须是不可为空的值类型才能在泛型类型或方法中将其用作参数T"
The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
是否可能将可为空类型指定为泛型参数?
Is specifying a nullable type as a generic parameter at all possible?
推荐答案
将返回类型改为Nullable
,并调用非空参数的方法
Change the return type to Nullable<T>
, and call the method with the non nullable parameter
static void Main(string[] args)
{
int? i = GetValueOrNull<int>(null, string.Empty);
}
public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
return (T)columnValue;
return null;
}
这篇关于可空类型作为泛型参数可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!