当前位置 : 主页 > 编程语言 > delphi >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
继续我之前关于使用VCL接口的调查. How to implement identical methods with 2 and more Classes? How to use Interface with VCL Classes? 我想有一个代码示例来演示两者在哪里以及如何协同工作. 或者两者的经典
继续我之前关于使用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;
想象一下,您有TSomeThing和TSomeThingElse类,但它们没有共同的祖先类.按原样,您将无法将它们传递给相同的函数,或者在它们上调用常用方法.通过向两个类添加共享接口,您可以同时执行这两个操作,例如:

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;
网友评论