在子类中使用自键型参数创建泛型类或接口

时间:2016-02-08 15:56:04

标签: delphi generics inheritance interface delphi-xe2

我想创建一个我可以继承的类或接口,总是使用当前的类实例作为方法参数......

以下是解释我的问题的示例:

 type IArithmeticObject = interface(IInterface)
   procedure assign(ao : IArithmeticObject);
   procedure add(ao : IArithmeticObject);
   procedure remove(ao : IArithmeticObject);
   procedure multiply(ao : IArithmeticObject);
   procedure divide(ao : IArithmeticObject);
 end;

接口IArithmeticObject可以作为起点,引用基本的算术运算,子类可以声明为

 type TInteger = class(TInterfacedObject, IArithmeticObject)
   procedure assign(ao : TInteger);
   procedure add(ao : TInteger);
   procedure remove(ao : TInteger);
   procedure multiply(ao : TInteger);
   procedure divide(ao : TInteger);
 end;

ao的参数类型为TInteger而不是IArithmeticObject

另一个想法是使用自引用泛型类型,如:

  AMathObject = class;

  AMathObject<T : AMathObject, constructor> = class
    procedure assign(ao : T);virtual;abstract;
    procedure add(ao : T);virtual;abstract;
    procedure remove(ao : T);virtual;abstract;
    procedure multiply(ao : T);overload;virtual;abstract;
    procedure divide(ao : T);virtual;abstract;
  end;

但我找不到合适的语法......

有没有人对这种可能性(或不可能性)有任何想法?

1 个答案:

答案 0 :(得分:3)

如果我没有正确理解它,您可能希望从通用接口派生您的类。

type
  IArithmeticObject<T> = interface
    procedure assign(ao: IArithmeticObject<T>);
    procedure add(ao: IArithmeticObject<T>);
    procedure remove(ao: IArithmeticObject<T>);
    procedure multiply(ao: IArithmeticObject<T>);
    procedure divide(ao: IArithmeticObject<T>);
  end;

  TInteger = class (TInterfacedObject, IArithmeticObject<TInteger>)
    procedure assign(ao: IArithmeticObject<TInteger>);
    procedure add(ao: IArithmeticObject<TInteger>);
    procedure remove(ao: IArithmeticObject<TInteger>);
    procedure multiply(ao: IArithmeticObject<TInteger>);
    procedure divide(ao: IArithmeticObject<TInteger>);
  end;

根据Stefan Glienke's comment编辑的答案:现在类的方法接受声明为对象或接口的参数。

var
  ao: IArithmeticObject<TInteger>;
begin
  ao := TInteger.Create;
  ao.multiply(ao);
end.