Home Returning an ObjectList from RTTI in delphi
Reply: 2

Returning an ObjectList from RTTI in delphi

John Published in 2018-02-08 16:40:54Z

i'm calling method inside an object and i'm trying to stay very dynamic in the way i'm doing it and i came to a problem where my return type is a list of some objects, i thought about using TObjectList the problem now is that rtti returns a TValue and i don't fully understand how i can convert it to TObjectList. I thought casting the TValue as TObject since theoritically TObjectList is an object but it didn't work. Do you guys have any idea how i can possibly achieve this?

That's the function i'm speaking about.

   function TMyClass.ExecMethodAndRet(MethodName: string;
      Args: array of TValue): TObjectList<TObject>;
     R : TRttiContext;
     T : TRttiType;
     M : TRttiMethod;
      T := R.GetType(FMyObject.ClassInfo);
      for M in t.GetMethods do
        if (m.Parent = t) and (UpperCase(m.Name) = UpperCase(MethodName))then
          result := M.Invoke(FMyObject, Args); <- problem here can't cast to TObjectList
Victoria Reply to 2018-02-08 17:02:39Z


Result := M.Invoke(Self, Args).AsType<TObjectList<TObject>>;

P.S. don't forget to initialize return value, ideally at the beginning of your function body.

Stefan Glienke
Stefan Glienke Reply to 2018-02-08 17:04:05Z

You need to call AsType on the TValue with the correct parameter. (see doc)

If you in fact have a TObjectList<TObject> then this should be passed. If you have some TObjectList<T> where T is some other class you need to do a hardcast like this:

Result := TObjectList<TObject>(M.Invoke(FMyObject, Args).AsObject);

By doing so you basically fake covariance. However keep in mind that because you can add objects to your returned TObjectList<TObject> you are losing type safety regarding what element type it really has and the list itself does not check that. (see my article about co- and contravariance).

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300664 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO