1

I have a problem, see if you can help me. I have a base form.

type
  TForm_Base = class(TForm)
  oObjectoVO : TObject;
  ...
  procedure Search<M:class,constructor>;
  ...
  procedure TForm_Base.Search<M>;
  begin
    TBussinesObj<M>.Pesquisa(FDMemTableGrid);
  end;

And I have a form that inherits the base form.

procedure TForm_Client.FormCreate(Sender: TObject);
begin
  // TClient is class simple with the properties(write, read) of id, name, ...
  oObjectoVO := TClient.Create;
end;

procedure TForm_Client.ButtonSearchClick(Sender: TObject);
begin
  inherited;
end;

procedure TForm_Client.FormDestroy(Sender: TObject);
begin
  FreeAndNil(oObjectoVO);
end;

My problem is here. I cannot pass the type of the object instantiated in the client form, to the generic method (Search ) to the base form. I don't know if it's possible.

procedure TForm_Base.ButtonSearchClick(Sender: TObject);
begin
  Search<oObjectoVO.ClassType>; ******* Error *******
end;

Tanks.

Neghetty
  • 13
  • 2

1 Answers1

3

Generics are a compile time construct. Consider this code:

Search<oObjectoVO.ClassType>

You are attempting to instantiate the generic with a type that is not known until run time.

You need to change Search from being a generic to being non-generic and accepting a parameter that specifies the class.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thanks for the feedback. Understand. I thought there might be some method from the RTTI library that would return the type of the class. The only way to get it right is by passing the class type on the Client form. (Search ;). Thanks again. – Neghetty Apr 24 '20 at 18:36
  • There are RTTI methods. But what you have to understand is the very first sentence in my answer. Generics are instantiated at compile time. RTTI is run time type information. You need to understand that run time information is not known at compile time. – David Heffernan Apr 24 '20 at 19:46
  • I understood my friend. Thanks again. The way I'm trying to do it doesn't really work. I will have to pass the type when calling the Search method. Thanks again. – Neghetty Apr 24 '20 at 20:37