【问题标题】:How to use Interface with VCL Classes - Part 2 [closed]如何将接口与 VCL 类一起使用 - 第 2 部分 [关闭]
【发布时间】:2012-01-10 20:27:30
【问题描述】:

继续我之前关于使用 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;

【问题讨论】:

  • 你需要问一个具体的问题。除非您对其进行适当的编辑,否则这很可能会吸引密切投票。
  • 我认为您应该清楚地说明一个具体问题。这是第 3 个问题,我不确定它们中的任何一个有什么不同。
  • 为什么不扩展共同祖先呢?
  • @user539484,你是对的,但最初的问题是针对 TCheckBoxTRadioButton 提出的,它们有第一个共同祖先 TButtonControl(不知道是否也在 Delphi 7 中)恕我直言,除了修改 VCL 源来实现这一点之外别无他法(D7 没有类助手或拦截类)。 OP 只是想加入两个课程,每个课程都有自己的方式。

标签: delphi delphi-7


【解决方案1】:

假设您有 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;

【讨论】:

  • 前面的问题都是关于实现继承的,当你不是从一个共同的祖先派生时,这在 Delphi 中当然是不可能的
  • 终于!第二个if Supports(O1, ISomething, Intf) 应该是O2 否?
  • 大卫,在前面的问题中,我意识到使用接口是没有用的。您发布的代码非常好,但它是我今天使用的一些代码。我希望它可以以其他方式完成(建议使用接口),但我无法意识到如何以及特别是何时使用它。 10x
  • Remy 现在给我的例子,为我清理了混乱(直到下一次:wink:)。
  • @GolezTrol 什么是聚合类?
猜你喜欢
  • 2010-09-23
  • 2016-12-01
  • 2017-12-02
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
相关资源
最近更新 更多