使用定义接口作为泛型参数

问题描述 投票:0回答:1

我正在尝试编写一个流畅的接口,其中我返回调用者调用中使用的相同接口以生成如下所示的代码,但也允许支持类是可继承的。

Result:=Imp.Add(5).Subtract(2).Value;

我的绊脚石是我无法在父接口的参数中使用定义接口,因为我收到此错误:

IImp 型尚未完全定义

type
  IAdd<T: IInterface> = interface
    function Add(Value: Integer): T;
  end;

  IAddSubtract<T: IInterface> = interface(IAdd<T>)
    function Subtract(Value: Integer): T;
  end;

//  IImp = interface;
  IImp = interface(IAddSubtract<IImp>)
    ['{B1CB6C84-B79C-4F01-8304-FD22CD7A1230}']
  end;
delphi interface
1个回答
0
投票

你的做法是完全错误的。如果您想拥有流畅的接口,那么您需要声明包含所有必需操作的单个接口,而不是多个接口。您也不需要泛型来做到这一点。

在更复杂的场景中,您可能需要切换到其他界面,类似于您现在想要在最后获取整数

Value
时所拥有的接口,但您的示例也不需要这样做。

这就是代码流畅界面的样子:

type
  ICalculator = interface
    function Add(AValue: Integer): ICalculator;
    function Subtract(AValue: Integer): ICalculator;
    function GetValue: Integer;
    property Value: Integer read GetValue;
  end;

  TCalculator = class(TInterfacedObject, ICalculator)
  protected
    FValue: Integer;
  public
    function Add(AValue: Integer): ICalculator;
    function Subtract(AValue: Integer): ICalculator;
    function GetValue: Integer;
    property Value: Integer read GetValue;
  end;

function TCalculator.GetValue: Integer;
begin
  Result := FValue;
end;

function TCalculator.Add(AValue: Integer): ICalculator;
begin
  FValue := FValue + AValue;
  Result := Self;
end;

function TCalculator.Subtract(AValue: Integer): ICalculator;
begin
  FValue := FValue - AValue;
  Result := Self;
end;

然后你就可以按照你想要的方式使用它了:

var
  Imp: ICalculator;
  Result: Integer;
begin
  Imp := TCalculator.Create;
  Result := Imp.Add(5).Subtract(2).Value;
  ...
© www.soinside.com 2019 - 2024. All rights reserved.