c# - DataRow 的通用字段 getter

标签 c# generics ado.net extension-methods datarow

我尝试使用此通用方法扩展 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 为 intdecimaldouble 等时,它工作正常

但是当我尝试使用 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/

相关文章:

c# - 如何通过 C# 检索所有可能的服务器名称

vb.net - 更新单个数据表行的最佳实践

c# - Asp.net MVC路由功能

c# - 确定 .NET Windows 服务是否未挂起的最佳方法?

c# - 在 C# MVC 应用程序中,是否可以从未更改的控件中的网页提交变量?

java - 如何将方法参数声明为任何枚举

Java 使用泛型对集合进行排序

c# - 使用类型为 DataType 的泛型方法

c# - 我可以从 SqlConnection 对象获取对挂起事务的引用吗?

c# - 使用 ASP.net 将 Highcharts 连接到数据库