【问题标题】:Delphi: calling a method of a subclass from an Interface referenceDelphi:从接口引用调用子类的方法
【发布时间】:2015-07-09 23:22:44
【问题描述】:

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

现在,我总是可以以通用的、后期自定义绑定的方式创建和调用服务,传递 (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的接口引用(自动引用计数)。

【问题讨论】:

    标签: delphi interface delphi-7


    【解决方案1】:

    制作接口来表示其他功能。例如:

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

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2020-02-20
      • 2018-01-15
      • 1970-01-01
      • 2016-05-29
      相关资源
      最近更新 更多