Get/Set sub properties ussing RTTI

前端 未结 2 669
轻奢々
轻奢々 2021-01-06 14:43

Given the following code snippet below, using GetPropValue(MyComponent,\'MySubComponent.Prop1\') raises an EPropertyError exception. How can I retrieve or set t

2条回答
  •  粉色の甜心
    2021-01-06 15:09

    The dot notation you used in your question is not supported.

    You need to get the Value of the SubComponent, then perform the Set and Get on the individual properties.

    var
      C: TRttiContext;
      MyComp : TMyComponent;
      MyCompType : TRttiInstanceType;
      MySubCompType : TRttiInstanceType;
      MySubComponentValue : TValue;
    begin
      MyComp := TMyComponent.create(Self); 
      ...
      // RTTI.Pas Method
      MyCompType :=  c.GetType(TMyComponent.ClassInfo) as TRttiInstanceType;
      MySubCompType := c.GetType(TMySubComponent.ClassInfo) as TRttiInstanceType;
      MySubComponentValue := MyCompType.GetProperty('MySubComponent').GetValue(MyComp);
    
      if Not MySubComponentValue.IsEmpty then
      begin
          MySubCompType.GetProperty('Prop1').SetValue(MySubComponentValue.AsObject,43);
      end;
    
     //TypInfo.pas Method
     SubComp := GetObjectProp(MyComp,'MySubComponent');
     if Assigned(SubComp) then
     begin
        SetPropValue(SubComp,'Prop1',5);
        prop1Value := GetPropValue(SubComp,'Prop1');
     end;
    
    end;
    

    The TypInfo.pas method will only work with published properties, you can get the public properties with the RTTI.pas method.

提交回复
热议问题