Mohamad
Mohamad

Reputation: 1117

Pass a class with Generic parameter to another class in Delphi

I have 2 classes in Delphi XE5 and pass one to another :

  TfrmBaseList = class(TForm)
  private
    FListOwner: TSystemBaseList<TSystemColumnEntity>;
  public
    constructor Create(AListOwner: TSystemBaseList<TSystemColumnEntity>); virtual;
  end

  TSystemBaseList<T: TSystemColumnEntity> = class(TPersistent)
  public
    procedure Execute;
    property SelectedValues: TObjectList<T> read 
  end;


  procedure TSystemBaseList<T>.Execute;
  var
    frmList: TfrmBaseList;
  begin
   //frmList := TfrmBaseList.Create(Self<T>)
   //frmList := TfrmBaseList.Create(Self<TSystemColumnEntity>)  
   frmList := TfrmBaseList.Create(???????)
  end;

How can I Pass TSystemBaseList to Constructor of TfrmBaseList class?

This constructor only create a Form and then assign AListOwner to FListOwner, Can I change this constructor to property like this:

TfrmBaseList = class(TForm)
private
  FListOwner: TSystemBaseList<TSystemColumnEntity>;
public
  property ListOwner: TSystemBaseList<TSystemColumnEntity> read FListOwner write FListOwner;
end

And how do I set it?

Upvotes: 1

Views: 680

Answers (1)

David Heffernan
David Heffernan

Reputation: 612964

The constructor expects a concrete instantiation, an instance of:

TSystemBaseList<TSystemColumnEntity>

You are supplying an uninstantiated generic instance of type:

TSystemBaseList<T>

You have to supply a concrete instance to that constructor. In its current form you cannot instantiate the form from TSystemBaseList<T>.Execute.

You might think that because T must derive from TSystemColumnEntity that TSystemBaseList<T> would be compatible with TSystemBaseList<TSystemColumnEntity>. But that is not the case because there is no generic variance supported. Read more on this topic here: Generics and variance.

One way forward would be to make the form type generic too. Although that does not play well with the IDE form designer. I suspect a more radical re-design is needed to solve your problem. I won't offer advice on that re-design because I don't know the problem.

Upvotes: 4

Related Questions