我想做这样的事:
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”。
是否可以将可空类型指定为泛型参数?
发布于 2008-10-16 16:04:01
将返回类型更改为Nullable<T>,并使用非空参数调用方法
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;
}发布于 2011-04-01 18:23:02
public static T GetValueOrDefault<T>(this IDataRecord rdr, int index)
{
object val = rdr[index];
if (!(val is DBNull))
return (T)val;
return default(T);
}就像这样用吧:
decimal? Quantity = rdr.GetValueOrDefault<decimal?>(1);
string Unit = rdr.GetValueOrDefault<string>(2);发布于 2008-10-16 23:48:18
只需对原始代码做两件事--删除where约束,并将最后一个return从return null更改为return default(T)。这样你就可以返回你想要的任何类型。
顺便说一句,您可以通过将is语句更改为if (columnValue != DBNull.Value)来避免使用if (columnValue != DBNull.Value)。
https://stackoverflow.com/questions/209160
复制相似问题