delphi – 调用从接口和另一个祖先继承的类的方法
我在实现某些类之间的关系时遇到问题.我有三个不同的课程,提供三种不同的形式.所有这些类都使用相同的语言,因此它们从名为TAncestorServer的同一类继承.让我们称它为后代TForm1Server,TForm2Server和TForm3Server. TAncestorServer包含一个名为Function1的抽象方法,因此TForm1,TForm2和TForm3可以通过它们自己继承的类来调用它,它们可以通过名为Server的属性访问类.但问题在于另一种称为TForm4的形式!它与其他形式非常相似,但它并不像他们那样独立.它适用于TForm2Server或TForm3Server.仍然不是问题,但想象另一种方法,如在TForm2Server和TForm3Server中声明的Function2,TForm4需要调用它们.我可以这样:
if Server is TForm2Server then TForm2Server(Server).Function2 else if Server is TForm3Server then TForm3Server(Server).Function2; 但它可以变成一个无限的if-else子句!所以我认为像多重继承这样的东西可能会有所帮助.我声明了一个名为IForm4Server的接口,它包含Function2.因此TForm2Server和TForm3Server继承自TAncestorServer和IForm4Server.我认为这样的事情可行: If Server is IForm4Server then IForm4Server(Server).Function2; 但是编译器不这么认为,它说它不是有效的类型转换,因为TAncestorServer不是IForm4Server,这是绝对正确的. TForm1Server不知道实现Function2,必须留空.我也不能将TForm4.Server声明为IForm4Server,因为Function1代表了大量的方法和属性,但是我仍然无法将类型转换为IForm4Server到TAncestorServer. 作为一个解决方案,我可以在TForm4中定义两个不同的属性,如GeneralServer:TAncestorServer和Form4Server:IForm4Server,然后为它们分配相同的TForm2Server或TForm3Server实例,但我感觉不太好.我该怎么做?它有什么标准模式吗? 解决方法
实现一个或多个接口是正确的方法,但看起来你对正确的语法有点困惑,并且没有接口经验.
基本的东西是: >对于任意数量的类,您都有一个共同的祖先类(或表单).祖先声明了类以某种方式专门化的虚方法. >使用祖先类多态调用任何虚方法 我做了一个我能想到的最简单的例子,使用视觉继承表单和简单的界面.该示例的摘录如下: 共同的祖先类: type TServerForm = class(TForm) private { Private declarations } public { Public declarations } procedure Method1; virtual; end; 界面: type IMyInterface = interface ['{B7102C7E-F7F6-492A-982A-4C55CB1065B7}'] procedure Method2; end; 孩子形成: 这个继承自TServerForm并实现接口 type TServerForm3 = class(TServerForm,IMyInterface) public procedure Method1; override; procedure Method2; end; 这个只是继承自TServerForm type TServerForm4 = class(TServerForm) public procedure Method1; override; end; 这个直接从TForm继承并实现接口 type TNoServerForm = class(TForm,IMyInterface) public procedure Method2; end; 所有表单都是自动创建的,然后,我有这个代码来调用另一个表单上的几个OnClick for按钮上的方法(应用程序示例的主要形式): 要基于多态调用虚方法: procedure TForm6.Button1Click(Sender: TObject); var I: Integer; begin for I := 0 to Screen.FormCount - 1 do begin if (Screen.Forms[I] is TServerForm) then TServerForm(Screen.Forms[I]).Method1; end; end; 要根据接口的实现调用该方法: procedure TForm6.Button2Click(Sender: TObject); var I: Integer; Intf: IMyInterface; begin for I := 0 to Screen.FormCount - 1 do begin if Supports(Screen.Forms[I],IMyInterface,Intf) then Intf.Method2; end; end; 方法只显示消息,一切正常: procedure TServerForm3.Method2; begin ShowMessage(ClassName + '.Method2'); end; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |