我如何使用RTTI设置嵌套属性的值 [英] how i can set the value of a nested property using the RTTI

查看:274
本文介绍了我如何使用RTTI设置嵌套属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查这个简化的样本(真实场景是不同的),我想设置一个对象的嵌套属性的值,在这种情况下设置一个 TLabel 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); //这行不工作
finally
c.Free;
结束
结束

我也试过

  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); //这行现在可以工作。
finally
c.Free;
结束
结束

您需要从标签中获取嵌入式字体。 TRttiProperty处理类型而不是实例。您需要调用 GetValue() SetValue()来处理该实例。



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


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);

解决方案

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.

这篇关于我如何使用RTTI设置嵌套属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆