Nullable type as a generic parameter possible?
I want to do something like this :
myYear = record.GetValueOrNull<int?>("myYear"),
Notice the nullable type as the generic parameter.
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:
The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method
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
Now the assignment:
myYear = record.GetValueOrNull<int?>("myYear");
Gives the following error:
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,然后使用非空参数调用该方法
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;
}
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);
Just do two things to your original code – remove the where
constraint, and change the last return
from return null
to return default(T)
. This way you can return whatever type you want.
By the way, you can avoid the use of is
by changing your if
statement to if (columnValue != DBNull.Value)
.
上一篇: 为什么C#禁止泛型属性类型?
下一篇: 可以使用可空类型作为通用参数?