Delphi:从接口(interface)引用调用子类的方法

标签 delphi interface delphi-7

我有一组派生自基类的类。 基类代表要调用的通用服务(实际上是一种 REST 客户端), 每个派生类都是每个特定服务(具有特定参数)的包装器。 请注意,我的基类实现了一个Interface

这是一些简化的代码:

IMyService = interface
  ['{049FBEBD-97A8-4F92-9CC3-51845B4924B7}']
  function GetResponseContent: String;
  // (let's say AParams is a comma-delimited list of name=value pairs) 
  procedure DoRequest(const AParams: String); overload;  // (1)
  property ResponseContent: String read GetResponseContent; 
end;

TMyBaseService = class(TInterfacedObject, IMyService)
protected
  FResponseContent: String;
  function GetResponseContent: String;
public
  procedure DoRequest(const AParams: String); overload;  // (1)
  property ResponseContent: String; 
end;

TFooService = class(TMyBaseService)
public
  // This specific version will build a list and call DoRequest version (1)
  procedure DoRequest(AFooParam1: Integer; AFooParam2: Boolean); overload; // (2)
end;

TBarService = class(TMyBaseService)
public
  // This specific version will build a list and call DoRequest version (1)
  procedure DoRequest(ABarParam1: String); overload;  // (3)
end;

现在,我始终可以以通用的后期自定义绑定(bind)方式创建和调用服务,传递“开放”参数列表,如 (1) 中所示,并祈祷:

var
  Foo, Bar: IMyService;
begin
  Foo := TFooService.Create;
  Bar := TBarService.Create;
  Foo.DoRequest('name1=value1,name2=value2'); 
end;

但是调用标记为 (2) 和 (3) 的特定 DoRequest 的最佳方法是什么?

我无法将接口(interface)引用转换为对象 TFooService(Foo).DoRequest(2, False),
我无法声明 Foo: TFooService 因为我需要使用 ARC(自动引用计数)的接口(interface)引用。

最佳答案

创建接口(interface)来表示其他功能。例如:

type
  IFooService = interface
    [GUID here]
    procedure DoRequest(AFooParam1: Integer; AFooParam2: Boolean); overload;
  end;

TFooService实现它

type
  TFooService = class(TMyBaseService, IFooService)
  ....

然后使用 as 来访问它:

var
  Foo: IMyService;
....
(Foo as IFooService).DoRequest(AFooParam1, AFooParam2);

关于Delphi:从接口(interface)引用调用子类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29964658/

相关文章:

arrays - 类的函数返回一个在类之后声明的数组

pointers - 在 Go 中调用接口(interface)指针上的方法

delphi - 不知何故,意外地混合 TEdit.Text 和 TLabel.Caption 毫无异常(exception)地工作吗?

delphi - 如何从DataSnap服务器返回DataSet?

delphi - 在 Delphi 中,如何从防火墙 API 中的 LocalPolicy.CurrentProfile.GloballyOpenPorts 获取枚举器

delphi - 如何将 DECLARE_HANDLE 和后续常量从 windef.h 转换为 Delphi

delphi - Rave 报告数据文本左

java - 为什么接口(interface)中只允许使用公共(public)方法?

java - 即使是单个学生或单个类(class),返回集合或集合的接口(interface)是一个好习惯吗?如果是,为什么?

delphi - 如何检测在 A TTabControl 中单击了不同的选项卡?