对象如何转换为接口?(50)

  • 主题发起人 主题发起人 wind_2005
  • 开始时间 开始时间
W

wind_2005

Unregistered / Unconfirmed
GUEST, unregistred user!
在代码中遇到了接口转换的问题,还望各位能给帮忙,非常感谢!代码如下:------------------------unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type //接口 IA = interface procedure A
end
//使用接口的类的父类 TA = class(TControl) end
//使用接口的类AA TAA = class(TA, IA) public procedure A
end
//使用接口的类B TB = class(TControl,IA) public procedure A
end
TForm1 = class(TForm) Button1: TButton
procedure FormCreate(Sender: TObject)
procedure FormDestroy(Sender: TObject)
procedure Button1Click(Sender: TObject)
private aList: TList
aA: TA
aB: TB
{ Private declarations } public { Public declarations } end;var Form1: TForm1;implementation{$R *.dfm}{ TAA }procedure TAA.A;begin ShowMessage('TAA.A');end;{ TB }procedure TB.A;begin ShowMessage('TB.A');end;procedure TForm1.FormCreate(Sender: TObject);begin aList := TList.Create
aA := TAA.Create(Self)
aB := TB.Create(Self)
aList.Add(aA)
aList.Add(aB);end;procedure TForm1.FormDestroy(Sender: TObject);begin if Assigned(aA) then FreeAndNil(aA)
if Assigned(aB) then FreeAndNil(aB)
if Assigned(aList) then FreeAndNil(aList);end;procedure TForm1.Button1Click(Sender: TObject);var i: Integer
ai : IA;begin for i := 0 to aList.Count - 1 do begin //这里,使用前先判断类型,再转换为相应类型去调用函数 if TControl(aList) is TAA then (TControl(aList) as TAA).A else if TControl(aList) is TB then (TControl(aList) as TB).A
//不用判断类型,直接转换为接口来调用函数,是否可以实现?  //下面语句报"Operator not applicable to this operand type." ai := (TControl(aList) as IA)
ai.A
end;end;end.
 
IA = interface ['{71A150D9-C1A1-4A67-8779-4FE76F698DA3}'] procedure A
end;------------- TObject(aList).GetInterface( IA, ai)
ai.A;
 
[:)]我也是刚刚才找到问题所在,不过还是谢谢znxia了
 

Similar threads

后退
顶部