检查这个简化的示例(真实场景是不同的),我想设置一个对象的嵌套属性的值,在这种情况下,使用RTTI将TLabel组件的Font颜色设置为clRed. var p : TRttiProperty; p2: TRttiProperty; c : TRttiContext;begin c
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;
您需要从Label获取嵌入字体. TRttiProperty处理类型而不是实例.您需要调用GetValue()或SetValue()来处理实例.
您的原始代码是引用类型而不是实例.
