简体   繁体   中英

How to initialize child class using function that returns a parent class?

I've extended the DataTable class as follows:

class DataTableExtended:DataTable
    {
        public void specialMethod()
        {}
    }

I want to parse an XML node into this child class, which I tried to do with the following:

public DataTableExtended parseNodeToDataTable()
        {
            DataSet ds = new DataSet();
            XmlNodeReader reader = new XmlNodeReader(this.resultNodes);
            ds.ReadXml(reader);
            DataTable dt = ds.Tables[1];
            DataTableExtended dte=(DataTableExtended) dt;
            return dt;
        }

It's throwing an InvalidCastException . From what I've read so far, this is because it's not possible to cast a parent class to a child class. Is that accurate? If so, I know I can rewrite the DataTableExtended constructor so that it accepts a DataTable argument and copies that table's information, but I was hoping that there's a more direct way of doing this.

I would write an extension method for DataTable instead of subclassing it

public static class DataTableExtensions
{
    public static void SpecialMethod(this DataTable dt)
    {
        //do something
    }
}

--

DataTable dt = .........
dt.SpecialMethod();

I like to read the : operator as is a . So a DataTableExtended is a DataTable . Note that this does not imply that a DataTable is a DataTableExtended , hence the failure to cast.

I think the best way of "casting" in this direction is to take an instance of the base class in your constructor, as you suggest.

Also see this answer .

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