开发者

Polymorphism in Delphi Generics

开发者 https://www.devze.com 2022-12-30 03:10 出处:网络
type TParent=class public member1:Integer; end; TChild=class(TParent) public member2:Integer; end; TGArray<T: TParent>=class
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开发者_Python百科
    g := TGArray<TChild>.Create;
    g.test.member2 := 1234;
  end.

g.test has to return an instance of the class. I tried multiple things:

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

The purpose of this is to create a generic array of classes. The array is stored inside the generic class and returns instances, but how?

If I accomplish this thing, I will shorten my code 3 times, but I cannot do it. Please suggest any solution.


You don't say what the error in #2 is, but I'll bet it tells you it requires a constructor constraint. Add one and it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消