简体   繁体   中英

Converting DataTable objects to custom class objects inheriting from DataTable

I want to create a class that will add some new methods helpful in using a DataTable class. I want to avoid static classes, so I created a class

MyDataTable : DataTable

and my methods there.

How can I convert DataTable objects to MyDataTable objects? I already tried

MyDataTable dt2 = (MyDataTable)dt;

But it returns a InvalidCastException.

I know now that it doesn't work this way. But I also have no idea how can I solve this. Can anyone help me with this?

Of course it causes an InvalidCastException since not every DataTable is of type MyDataTable . You need to create an instance of your type:

MyDataTable myTable = new MyDataTable();

Normally i provide the most used constructors of the type i'm inheriting from. You can call the base constructor from the constructor of your type. So for example:

public class MyDataTable : DataTable
{
    public MyDataTable(string name)
        : base(name)
    {
        // additional initialization
    }
}

您甚至可以为从DataTable继承的自定义类编写隐式强制转换。

The following articles outlines how to extend from DataTables and DataRows:

http://www.internetworkconsulting.net/extending-data-tables-and-rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM