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

Delphi: calling a method of a subclass from an Interface reference

我有一组 class 派生自基数 class。 base class 表示要调用的通用服务(实际上是一种 REST 客户端), 每个派生的 class 是每个特定服务(具有特定参数)的包装器。 请注意,我的基础 class 实现了 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;

现在,我总是可以以通用的、后期自定义绑定的方式创建和调用服务,传递 "open" 参数列表,如 (1) 祈祷:

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

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

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

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

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);