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.
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.