Delphi 如何使用RTTI设置嵌套属性的值

Delphi 如何使用RTTI设置嵌套属性的值,delphi,delphi-xe,rtti,Delphi,Delphi Xe,Rtti,检查这个简化示例(实际场景不同),我想设置对象嵌套属性的值,在本例中,使用RTTI将TLabel组件的字体颜色设置为clRed var p : TRttiProperty; p2: TRttiProperty; c : TRttiContext; begin c := TRttiContext.Create; try p := c.GetType(Label1.ClassInfo).GetProperty('Font'); p2 := c.GetTyp

检查这个简化示例(实际场景不同),我想设置对象嵌套属性的值,在本例中,使用RTTI将
TLabel
组件的字体颜色设置为
clRed

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;
我也试过了

p2.SetValue(Label1,clred);

下面的代码将起作用

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;
您需要从标签中获取嵌入字体。trtti属性处理类型而不是实例。您需要调用
GetValue()
SetValue()
来处理该实例

您的原始代码引用的是类型,而不是实例