Delphi泛型中的多态性

4
type 
  TParent=class
    public
      member1:Integer;
  end;

  TChild=class(TParent)
  public
    member2:Integer;
  end;


  TGArray<T: TParent>=class
    public
      function test:T;
    end;

  implementation

  var g:TGArray<TChild>;

    function TGArray<T>.test:T;
    begin
      Result:=??.create; // <<<<  Problem !
    end;


  begin
    g := TGArray<TChild>.Create;
    g.test.member2 := 1234;
  end.

g.test必须返回该类的实例。我尝试了多种方法:

1.  Result := Result.create; //Exception
2.  Result := TChildClass.Create; //Error
3.  type TGArray<T: class> = class; //and above 2. The same errors/exceptions.

这个目的是创建一个通用的类数组。该数组存储在通用类中并返回实例,但是如何实现呢?

如果我能够完成这件事情,我将可以缩短我的代码三倍,但是我无法做到。请提供任何解决方案。

1个回答

7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接