Home Returning an ObjectList from RTTI in delphi

# Returning an ObjectList from RTTI in delphi

John
1#
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; var R : TRttiContext; T : TRttiType; M : TRttiMethod; begin T := R.GetType(FMyObject.ClassInfo); for M in t.GetMethods do if (m.Parent = t) and (UpperCase(m.Name) = UpperCase(MethodName))then begin result := M.Invoke(FMyObject, Args); <- problem here can't cast to TObjectList end; end; 
Victoria
2#
Victoria Reply to 2018-02-08 17:02:39Z
 Return: Result := M.Invoke(Self, Args).AsType>;  P.S. don't forget to initialize return value, ideally at the beginning of your function body.
Stefan Glienke
3#
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 then this should be passed. If you have some TObjectList where T is some other class you need to do a hardcast like this: Result := TObjectList(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 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.
Processed in 0.300664 second(s) , Gzip On .