如何使用VCL类接口 - 第2部分

时间:2012-01-10 20:27:30

标签: delphi delphi-7

继续我之前关于使用Interface with VCL的调查。

How to implement identical methods with 2 and more Classes?

How to use Interface with VCL Classes?

我想有一个代码示例来演示两者一起工作的位置和方式。 或者两者的经典利益/用法是什么:

ISomething = interface
['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}']
...
end;

TSomeThing = class(TSomeVCLObject, ISomething)
...
end;

1 个答案:

答案 0 :(得分:5)

想象一下,您有TSomeThingTSomeThingElse个类,但它们没有共同的祖先类。按原样,您将无法将它们传递给相同的函数,或者在它们上调用常用方法。通过向两个类添加共享接口,您可以同时执行这两个操作,例如:

type
  ISomething = interface 
  ['{EFE0308B-A85D-4DF3-889C-40FBC8FE84D0}'] 
  public
    procedure DoSomething;
  end; 

  TSomeThing = class(TSomeVCLObject, ISomething) 
    ... 
    procedure DoSomething;
  end; 

  TSomeThingElse = class(TSomeOtherVCLObject, ISomething) 
    ... 
    procedure DoSomething;
  end; 

procedure TSomeThing.DoSomething;
begin
  ...
end; 

procedure TSomeThingElse.DoSomething;
begin
  ...
end; 

procedure DoSomething(Intf: ISomething);
begin
  Intf.DoSomething;
end;

procedure Test;
var
  O1: TSomeThing;
  O2: TSomeThingElse;
  Intf: ISomething;
begin
  O1 := TSomeThing.Create(nil);
  O2 := TSomeThingElse.Create(nil);
  ...
  if Supports(O1, ISomething, Intf) then
  begin
    Intf.DoSomething;
    DoSomething(Intf);
  end;
  if Supports(O2, ISomething, Intf) then
  begin
    Intf.DoSomething;
    DoSomething(Intf);
  end;
  ...
  O1.Free;
  O2.Free;
end;