how i can set the value of a nested property using the RTTI

安稳与你 提交于 2019-12-21 05:28:30

问题


Check this simplified sample (the real scenario is different), I want to set tne value of a nested property of a object, in this case set the color of the Font for a TLabel component to clRed using RTTI.

var
  p : TRttiProperty;
  p2: TRttiProperty;
  c : TRttiContext;
begin
   c := TRttiContext.Create;
   try
     p := c.GetType(Label1.ClassInfo).GetProperty('Font');
     p2 := c.GetType(p.PropertyType.Handle).GetProperty('Color');
     p2.SetValue(p.PropertyType.AsInstance,clred); //this line is not working
   finally
     c.Free;
   end;
end;

also i tried

p2.SetValue(Label1,clred);

回答1:


The following code will work.

var
  p : TRttiProperty;
  p2: TRttiProperty;
  c : TRttiContext;
begin
   c := TRttiContext.Create;
   try
     p := c.GetType(Label1.ClassInfo).GetProperty('Font');
     p2 := c.GetType(p.PropertyType.Handle).GetProperty('Color');
     p2.SetValue(p.GetValue(Label1).AsObject,clred); //this line now works.
   finally
     c.Free;
   end;
end;

You need to get the Embedded Font from the Label. TRttiProperty deal with types and not instances. You need to call GetValue() or SetValue() to deal with the instance.

Your original code was referencing the type and not the instance.



来源:https://stackoverflow.com/questions/6006326/how-i-can-set-the-value-of-a-nested-property-using-the-rtti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!