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