我尝试使用此通用方法扩展 DataRow 对象:
public static T? Get<T>(this DataRow row, string field) where T : struct
{
if (row.IsNull(field))
return default(T);
else
return (T)row[field];
}
当 T 为 int
、decimal
、double
等时,它工作正常
但是当我尝试使用 with string 时,出现了这个错误:
"The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'"
我该如何纠正这个问题?
我知道字符串不是结构体,但如果字符串字段为 DBNull,我不想返回 null。
最佳答案
我想这就是你想要的:
public static T? GetValue<T>(this DataRow row, string field) where T : struct
{
if (row.IsNull(field))
return new T?();
else
return (T?)row[field];
}
public static T GetReference<T>(this DataRow row, string field) where T : class
{
if (row.IsNull(field))
return default(T);
else
return (T)row[field];
}
关于c# - DataRow 的通用字段 getter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4947868/