How can I get the sub-item type of a TObjectList purely by RTTI information (i.e. without using any actual object instance) in Delphi?

前端 未结 2 1131
一个人的身影
一个人的身影 2020-12-18 17:05

I\'m implementing generic code for streaming arbitrary Delphi objects using RTTI, and in order to get this to work (more specifically, in order to get the loading part to wo

2条回答
  •  执笔经年
    2020-12-18 17:57

    I've been looking for a solution about this and I had an ideia that I'd like to share with you. That solution uses rtti and get the method's argument "Add" from a list(TList,TObjectList,etc). In my function I just return the Class Type, but you can easyly implements to primivite types. I hope it can help someone. Regards.

    Folow:

    class function TUtilRtti.GetSubTypeItemClassFromList(ObjectList: TObject): TClass;
    var
      ctxRtti  : TRttiContext;
      typeRtti : TRttiType;
      atrbRtti : TCustomAttribute;
      methodRtti: TRttiMethod;
      parameterRtti: TRttiParameter;
    begin
      result := nil;
    
      ctxRtti  := TRttiContext.Create;
      typeRtti := ctxRtti.GetType( ObjectList.ClassType );
      methodRtti := typeRtti.GetMethod('Add');
      for parameterRtti in methodRtti.GetParameters do
      begin
        if SameText(parameterRtti.Name,'Value') then
        begin
          if parameterRtti.ParamType.IsInstance then
            result := parameterRtti.ParamType.AsInstance.MetaclassType;
          break;
        end;
      end;
      ctxRtti.Free;
    end;
    

    Sample

    ...
    var
      List: TList;
    begin
      List := TList.Create();
    
      ShowMessage(TUtilRtti.GetSubTypeItemClassFromList(List).ClassName);
    end;
    

提交回复
热议问题