我有一组派生自基类的类。
基类代表要调用的通用服务(实际上是一种 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/