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.

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

如果我完成这件事,我会缩短我的代码 3 倍,但我做不到。请提出任何解决方案。

4

1 回答 1

7

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

于 2010-05-14T18:02:41.003 回答