我使用扩展方法检查DataRowField是否为空。
public static string GetValue(this System.Data.DataRow Row, string Column)
{
if (Row[Column] == DBNull.Value)
{
return null;
}
else
{
return Row[Column].ToString();
}
}现在我想知道我能不能让这个更通用。在我的例子中,返回类型总是字符串,但列也可以是Int32或DateTime。
有点像
public static T GetValue<T>(this System.Data.DataRow Row, string Column, type Type)发布于 2016-09-27 11:52:14
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如果大小写不匹配,则列名查找要慢一些,因为先尝试更快的区分大小写的查找,然后再进行不区分大小写的搜索。。
发布于 2016-09-27 11:53:32
您的方法的签名如下
public static T GetValue<T>(this System.Data.DataRow Row, string Column)在其他部分,只需更改以下内容
return (T)Row[Column];https://stackoverflow.com/questions/39723298
复制相似问题