本文介绍了在delphi中的父类和子类之间进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些针对两个非常相似的硬件版本的软件,直到我使用API​​初始化硬件之前,我不知道我将返回哪种类型.

I'm writing some software that targets two versions of very similar hardware which, until I use the API to initialize the hardware I'm not able to know which type I'll be getting back.

因为硬件非常相似,所以我计划有一个父类(TParent),该类具有一些抽象方法(针对不同的硬件),然后有两个子类(TChildA,TChildB),它们以硬件相关的方式实现这些方法

Because the hardware is very similar I planned to have a parent class (TParent) that has some abstract methods (for where the hardware differs) and then two child classes (TChildA, TChildB) which implement those methods in a hardware dependent manner.

因此,我将首先实例化TParent的对象,检查它的类型,然后将其强制转换为正确的子对象.

So I would first instantiate an object of TParent check what kind it is then cast it to the correct child.

但是,当我执行此操作并调用在子类中完全实现的抽象方法之一时,会收到EAbstractError.

However when I do this and call one of the abstract methods fully implemented in the child class I get an EAbstractError.

例如:

myHardware:=TParent.Create();

if myHardware.TypeA then
   myHardware:=TChildA(myHardware)
else
   myHardware:=TChildB(myHardware);

myHardware.SomeMehtod();

我假设我不能将父类转换为子类,而且可能还有更好的方法.有指针吗?

I'm assuming that I can't cast a Parent Class to a child class, and also that there's probably a better way of doing this. Any pointers?

推荐答案

您是对的,您不能也不应从基类转换为派生类.

You're right, you can't and shouldn't cast from base class to derived class.

我假设您不想让Child对象重新运行Parent构造函数?

I'm assuming you don't want to have the Child object re-run the Parent constructor?

如果是这样. .

删除现有的父子关系,您将只有一个硬件类.对于特定的ChildA和ChildB功能,请创建一个新的继承模式,以便您具有ISpecificHardwareTasks接口或基类,以及两个派生类(SpecificA& B).

Remove the Parent/Child relationship as it stands, you will have only one Hardware class.For the specific ChildA and ChildB functionality, create a new inheritance pattern, so that you have an ISpecificHardwareTasks interface or base class, and two derived classes (SpecificA & SpecificB).

当硬件在构造它自己时,它会知道自己正在使用哪种类型的硬件,然后创建一个SpecificA或SpecificB的实例.该实例是硬件专用的.

When Hardware is constructing it's self, and it gets to the point where it knows what type of hardware it's working with, it then creates an instance of SpecificA or SpecificB). This instance is private to Hardware.

硬件公开了包装ISpecificHardWareTasks方法的方法(如果有意义,它甚至可以实现该接口).

Hardware exposes methods which wrap the ISpecificHardWareTasks methods (it can even implement that interface if that makes sense).

如果有必要,Specialty类可以引用Hardware类(尽管我不知道您是否可以在构造函数中访问this指针,但是我的Delphi变得生疏了)

The Specific classes can take a reference to the Hardware class, if that's necessary (though I don't know if you have access to the this pointer in a constructor, my Delphi is getting rusty)

希望这些杂乱无事对他们有帮助.

Hope these ramblings helped somewhat.

这篇关于在delphi中的父类和子类之间进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:30