Polymorphism in Delphi Generics

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 should return an instance of the class. I have tried several 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 common array of classes. The array is stored inside the general class and returns instances, but how?

If I do this, I will cut my code 3 times, but I cannot do this. Please suggest any solution.

+4
source share
1 answer

You won’t say what error is in # 2, but I bet that he tells you. requires constructor constraint. Add one and it should work.

+7
source

Source: https://habr.com/ru/post/1309801/


All Articles