how i can set the value of a nested property using the RTTI
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;
al开发者_开发问答so i tried
p2.SetValue(Label1,clred);
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.
精彩评论