Delphi泛型中的多态性

Iva*_*nov 4 delphi generics delphi-2009 generic-programming delphi-2010

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.
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

这样做的目的是创建一个通用的类数组.数组存储在泛型类中并返回实例,但是如何?

如果我完成这件事,我会缩短我的代码3次,但我不能这样做.请建议任何解决方案.

Mas*_*ler 7

你没有说#2中的错误是什么,但我敢打赌它告诉你它需要一个构造函数约束. 添加一个它应该工作.