如何通过Delphi RTTI为嵌套属性赋值?

更新于
2026-10-04 17:31:08
1阅读来源:SEO资源
  • 内容介绍
  • 相关推荐

本文共计279个文字,预计阅读时间需要2分钟。

检查以下简化的示例(实际场景可能不同),我想设置一个对象的嵌套属性的值。在这种情况下,使用RTTI将TLabel组件的字体颜色设置为clRed。

pascalvar p: TRttiProperty; p2: TRttiProperty; c: TRttiContext;begin c :=TRttiContext.Create; p :=c.GetProperty('TLabel.Font.Color'); p2 :=c.GetProperty('TLabel'); p.SetValue(p2.GetValue, clRed);end;

检查这个简化的示例(真实场景是不同的),我想设置一个对象的嵌套属性的值,在这种情况下,使用RTTI将TLabel组件的Font颜色设置为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;

您需要从Label获取嵌入字体. TRttiProperty处理类型而不是实例.您需要调用GetValue()或SetValue()来处理实例.

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

本文共计279个文字,预计阅读时间需要2分钟。

检查以下简化的示例(实际场景可能不同),我想设置一个对象的嵌套属性的值。在这种情况下,使用RTTI将TLabel组件的字体颜色设置为clRed。

pascalvar p: TRttiProperty; p2: TRttiProperty; c: TRttiContext;begin c :=TRttiContext.Create; p :=c.GetProperty('TLabel.Font.Color'); p2 :=c.GetProperty('TLabel'); p.SetValue(p2.GetValue, clRed);end;

检查这个简化的示例(真实场景是不同的),我想设置一个对象的嵌套属性的值,在这种情况下,使用RTTI将TLabel组件的Font颜色设置为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;

您需要从Label获取嵌入字体. TRttiProperty处理类型而不是实例.您需要调用GetValue()或SetValue()来处理实例.

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