如何编写DataTable.Rows [i] [j]的扩展方法? [英] How to write an extension method for DataTable.Rows[i][j]?

查看:117
本文介绍了如何编写DataTable.Rows [i] [j]的扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个扩展方法,如下所述(甚至可能)实现,该扩展方法与 .ToString()扩展方法类似。有人能指出我正确的方向吗?我试图在Google中搜索它,但找不到任何内容。

I would like to create an extension method to be implemented like below (if it is even possible) which would be similar to the .ToString() extension method. Can someone please point me in the right direction. I attempted to search it in Google and cannot locate anything.

DataTable table = db.GetInfo(UserId);
if (table.Rows.Count > 0)
{
     bool b = table.Rows[0]["ColumnName"].MyExtensionMethod();
}

我基本上想简化一下:

bool b = Convert.IsDBNull(table.Rows[0]["ColumnName"]) ? false : bool.Parse(table.Rows[0]["ColumnName"].ToString());

bool b = table.Rows[0]["ColumnName"].DbBoolNullable();


推荐答案

由于 DataRow的索引器返回System.Object,您最好的选择是以下:

Since the indexer of DataRow returns a System.Object, your best bet is something like the following:

public static class Extensions
{
    public static bool DbBoolNullable(this object o)
    {
        return Convert.IsDBNull(o) ? false : bool.Parse(o.ToString());
    }
}

但是,我强烈建议,因为这是 System.Object 的扩展方法(.NET中的每个类都继承自此方法),所以此方法将应用于每个变量

However, I'd strongly advise against this, as since this is an extension method for System.Object (which every class in .NET inherits from), then this method will apply to every variable.

更好的方法可能是为 DataRow 创建扩展方法:

A better way would probably to make an extension method for DataRow:

public static bool GetBool(this DataRow row, string column)
{
   return Convert.IsDbNull(row[column]) ? false : bool.Parse(row[column].ToString());
}

然后您可以像这样使用它:

Then you could use it like so:

bool val = table.Rows[0].GetBool("ColumnName");

这篇关于如何编写DataTable.Rows [i] [j]的扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆