将对象转换为派生类中的对象 [英] Cast an object into an object from a derived class
问题描述
我有一个很好的类Record
:
public class Record
{
protected string table;
protected string idcolumn;
public Record(string _table, string _idcol, int _id)
{
table = _table;
idcolumn = _idcol;
Id = _id;
}
}
我还有一个类Order
,它是从Record
派生的,该类实现了额外的方法,仅适用于某种记录类型:
I also have a class Order
that is derived from Record
, that implements extra methods, only applicable on a certain type of record:
class Order : Record
{
public void Start()
{
}
}
在我的应用程序中,我有一个类型为Record
的对象theRecord
,我想将其强制转换为Order
,以便可以在其上调用Start
方法.
In my application, I have an object theRecord
of type Record
that I want to cast to Order
, so that I can call the Start
method on it.
我尝试投射它:
Order r = (Order)theRecord;
但是会抛出一个InvalidCastException
.
我认为我可以为Order
创建一个新的构造函数,该构造函数采用Record
,但是我已经有了该对象(通过从数据库中获取记录来构建该对象).
I am thinking that I could create a new constructor for Order
that takes a Record
, but I already have the object (which is built by fetching a record from the database).
我该如何正确实现呢?
推荐答案
我在评论中说
您可以将一只狗投向动物,但不能将动物投向狗(除非该动物是狗).更清晰所有的狗都是动物,但并非所有的动物都是狗
You can cast a Dog to Animal but not Animal to Dog(unless that animal is Dog). More clearer All Dogs are Animal but not all Animals are Dogs
Record record = new Record();
Order order = (Order)record;//wont work since record is some record not an Order
要使其正常工作,您必须执行以下操作
To make it work you've to do something like this
Record record = new Order();
然后您可以像这样投射它
Then you can cast it like this
Order order = (Order)record;//works since record is Order
这篇关于将对象转换为派生类中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!