通用数据行扩展

Generic DataRow extension

我使用扩展方法检查 DataRowField 是否为 null

public static string GetValue(this System.Data.DataRow Row, string Column)
{
    if (Row[Column] == DBNull.Value)
    {
        return null;
    }
    else
    {
        return Row[Column].ToString();
    }
}

现在我想知道我是否可以使它更通用。在我的例子中,return 类型始终是字符串,但 Column 也可以是 Int32 或 DateTime

类似

public static T GetValue<T>(this System.Data.DataRow Row, string Column, type Type)
public static T value<T>(this DataRow row, string columnName, T defaultValue = default(T)) 
    => row[columnName] is T t ? t : defaultValue;

或对于早期的 C# 版本:

public static T value<T>(this DataRow row, string columnName, T defaultValue = default(T))
{
    object o = row[columnName];
    if (o is T) return (T)o; 
    return defaultValue;
}

示例使用(基础类型必须完全匹配,因为没有转换):

int i0 = dr.value<int>("col");       // i0 = 0 if the underlying type is not int

int i1 = dr.value("col", -1);        // i1 = -1 if the underlying type is not int

没有扩展名的其他替代方案可以是可空类型:

string s = dr["col"] as string;      // s = null if the underlying type is not string 

int? i = dr["col"] as int?;          // i = null if the underlying type is not int

int i1 = dr["col"] as int? ?? -1;    // i = -1 if the underlying type is not int

如果大小写不匹配,列名查找会变慢,because a faster case sensitive lookup is attempted first before the slower case insensitive search

您的方法签名如下

public static T GetValue<T>(this System.Data.DataRow Row, string Column)

在Else部分只需更改以下内容

return (T)Row[Column];