Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通用数据行扩展_C#_Datarow - Fatal编程技术网

C# 通用数据行扩展

C# 通用数据行扩展,c#,datarow,C#,Datarow,我使用扩展方法检查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(); } } 现在我想知道我是否可以

我使用扩展方法检查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();
    }
}
现在我想知道我是否可以让它更通用。在我的例子中,返回类型始终是string,但列也可以是Int32或DateTime

差不多

public static T GetValue<T>(this System.Data.DataRow Row, string Column, type Type)
public static T GetValue(此System.Data.DataRow行、字符串列、类型)

如果大小写不匹配,列名查找会变慢。

方法的签名如下

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

如果字符串是int或DateTime,为什么要返回它?使用强类型甚至支持可为空类型的。返回“对象”而不是字符串。还要更改以下内容:if((对象)行[列]==DBNull.Value)。然后,您不必将强制转换单元格值返回到字符串。如果需要更健壮的方法,可以使用
Convert.ChangeType
代替强制转换。
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
public static T GetValue<T>(this System.Data.DataRow Row, string Column)
return (T)Row[Column];