[英]How to initialize child class using function that returns a parent class?
I've extended the DataTable
class as follows: 我已经扩展了DataTable
类,如下所示:
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: 我想将XML节点解析为此子类,我尝试使用以下内容:
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
. 它抛出了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. 如果是这样,我知道我可以重写DataTableExtended
构造函数,以便它接受一个DataTable
参数并复制该表的信息,但我希望有更直接的方法来做到这一点。
I would write an extension method for DataTable instead of subclassing it 我会为DataTable编写一个扩展方法,而不是对它进行子类化
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
. 我喜欢读:
操作者is a
。 So a DataTableExtended
is a DataTable
. 所以DataTableExtended
是一个DataTable
。 Note that this does not imply that a DataTable
is a DataTableExtended
, hence the failure to cast. 请注意,这并不意味着一个DataTable
是DataTableExtended
,因此投了故障。
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 . 另见这个答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.