Delphi中使用RTTI获取组件的子属性 [英] Get a sub property of a component in Delphi using RTTI

查看:22
本文介绍了Delphi中使用RTTI获取组件的子属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I would like to access the following property using RTTI

MyComponent1.Property['variable'].SubProperty

I would like something like that:

var
  Ctx: TRttiContext;
  Typ: TRttiType;
  SubTyp: TRttiType;
  Prop: TRttiProperty;
  SubProp: TRttiProperty;
begin
  Ctx:= TRttiContext.Create;
  Typ:= Ctx.GetType(MyComponent1.ClassInfo);
  Prop:= Typ.GetProperty('Property['variable'].Subproperty') //not possible
  Prop.SetValue(MyComponent1.Property['variable'],'500');
end;

Basically I want to access a subproperty of my component and I have only strings, so I cannot use Typ:=Ctx.GetType(MyComponent1.ClassInfo) and then Prop:=Typ.GetProperty('Property['variable'].Subproperty') this is not allowed. Attention in the fact that there is a paramenter for the first property. I guess I have to obtain this first property and then somehow the second property, because I cannot use this property1"."property2
Does anyone know how to do that?

解决方案

Index properties as all other properties (except direct references to object fields) just a shortcut to getXXX and setXXX methods.

Try that way:

  1. Get all indexed properties of Ctx.GetType(MyComponent1.ClassInfo) with GetDeclaredIndexedProperties or GetIndexedProperties

  2. Search desired Property in returned array of TRttiIndexedProperty instances.

  3. Get write method description object from WriteMethod property of TRttiIndexedProperty object found.

  4. Get method parameters description if you need it with GetParameters call.

  5. Call Invoke method of method description object with constructed parameter(s) list to set a property value.

Update

This works only in Delphi versions from XE2 and above.

In previous versions indexed properties can be adopted for RTTI only using things like discussed in this question.

这篇关于Delphi中使用RTTI获取组件的子属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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