Search code examples
delphigenericscastingdelphi-2010

Cast member of generic type to TObject?


I am currently thinking about a scenario where I want a generic class that calls Free on its items IF these are of an object type. So I tried the following:

if (PTypeInfo (TypeInfo (T)).Kind = tkClass) then
  begin
  RttiType := RttiContext.GetType (TypeInfo (T));
  FreeMethod := RttiType.GetMethod ('Free');
  if (FreeMethod <> nil) then
    FreeMethod.Invoke (FInstance, []);
  end;

Unfortunately the last line does not compile, which is not surprising since the types do not match. The question is: can I get it to compile? I tried casting to Pointer and then to TObject but that gives me an invalid typecast error. Is there any way to get FInstance : T into a TObject reference that I can then pass to Invoke?

Or is there any other way to achieve what I want? Please note that the whole point is to get everything in this class, so I do not want to create a TObjectMyClass that just takes objects.

Thanks for your help.


Solution

  • Isn't this sufficient?

    if PTypeInfo(TypeInfo(T))^.Kind = tkClass then
      TObject(FInstance).Free;