0

我在下面定义了一个基类测试

type
Tinfo = procedure of object;

Test = class(TObject)
public
  procedure Add    ( const a : Tinfo ); reintroduce ;
end;


procedure Test.Add(const a: Tinfo);
begin
  Writeln('base class add function');
  // dosomething more  
end;

我有一个从这个基类派生的泛型类

TTesting<T> = class(Test)
   public
     procedure Add    ( const a : T  ); reintroduce ;
   end;

我正在类型转换TTinfo但它给了我错误

procedure TTesting<T>.Add(const a : T );
begin
  inherited Add(Tinfo(a) );  // gives me error here 
end;

有什么办法可以实现吗?

4

1 回答 1

1

首先你的演员是错误的,你显然想演员而不是T。

但是,如果您想在对象过程上进行类型转换,该对象是一种不能以任何方式多态的类型,那么将其放入泛型类型根本没有意义。

T 应该是什么?它只能是代码中的 TInfo。

但是,如果您希望 T 成为任何事件/方法类型,则应将 TMethod 存储在基类中,然后在泛型类中使用它。但请记住,您不能有将 T 限制为事件类型的约束。所以你可以在你的构造函数中检查它。

type
  PMethod = ^TMethod;

  Test = class(TObject)
  public
    procedure Add(const a: TMethod ); reintroduce ;
  end;

procedure Test.Add(const a: TMethod);
begin
  Writeln('base class add function');
  // dosomething more
end;

type
  TTesting<T> = class(Test)
  public
    constructor Create;
    procedure Add(const a: T); reintroduce ;
  end;

constructor TTesting<T>.Create;
begin
  Assert(PTypeInfo(TypeInfo(T)).Kind = tkMethod);
  inherited Create;
end;

procedure TTesting<T>.Add(const a: T);
begin
  inherited Add(PMethod(@a)^);
end;
于 2014-11-10T11:06:42.050 回答