首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通用DataRow扩展

通用DataRow扩展
EN

Stack Overflow用户
提问于 2016-09-27 11:19:11
回答 2查看 1.7K关注 0票数 3

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

代码语言:javascript
复制
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。

有点像

代码语言:javascript
复制
public static T GetValue<T>(this System.Data.DataRow Row, string Column, type Type)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-27 11:52:14

代码语言:javascript
复制
public static T value<T>(this DataRow row, string columnName, T defaultValue = default(T)) 
    => row[columnName] is T t ? t : defaultValue;

或者对于早期的C#版本:

代码语言:javascript
复制
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;
}

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

代码语言:javascript
复制
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

没有扩展的其他选项可以是可空类型:

代码语言:javascript
复制
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

如果大小写不匹配,则列名查找要慢一些,因为先尝试更快的区分大小写的查找,然后再进行不区分大小写的搜索。

票数 6
EN

Stack Overflow用户

发布于 2016-09-27 11:53:32

您的方法的签名如下

代码语言:javascript
复制
public static T GetValue<T>(this System.Data.DataRow Row, string Column)

在其他部分,只需更改以下内容

代码语言:javascript
复制
return (T)Row[Column];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39723298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档