获取/设置使用RTTI的子属性 [英] Get/Set sub properties ussing RTTI
问题描述
鉴于以下代码片段,使用 GetPropValue(MyComponent,'MySubComponent.Prop1')
引发了EPropertyError异常。
如何使用GetPropValue / SetPropValue检索或设置SubProperties的值?
Given the following code snippet below, using GetPropValue(MyComponent,'MySubComponent.Prop1')
raises an EPropertyError exception.
How can I retrieve or set the values of SubProperties using GetPropValue / SetPropValue?
Type
TMySubComponent = class(TInterfacedPersitent)
private
FProp1: Integer;
published
property Prop1: integer read FProp1 write FProp1;
end;
TMyComponent = class(TCompoent)
private
FMySubComponent : TMySubcomponent;
published
property MySubComponent: TMySubComponent read FMySubComponent write FMySubComponent ;
end;
推荐答案
不支持您在问题中使用的点符号
The dot notation you used in your question is not supported.
您需要获取SubComponent的值,然后对各个属性执行Set和Get。
You need to get the Value of the SubComponent, then perform the Set and Get on the individual properties.
var
C: TRttiContext;
MyComp : TMyComponent;
MyCompType : TRttiInstanceType;
MySubCompType : TRttiInstanceType;
MySubComponentValue : TValue;
begin
MyComp := TMyComponent.create(Self);
...
// RTTI.Pas Method
MyCompType := c.GetType(TMyComponent.ClassInfo) as TRttiInstanceType;
MySubCompType := c.GetType(TMySubComponent.ClassInfo) as TRttiInstanceType;
MySubComponentValue := MyCompType.GetProperty('MySubComponent').GetValue(MyComp);
if Not MySubComponentValue.IsEmpty then
begin
MySubCompType.GetProperty('Prop1').SetValue(MySubComponentValue.AsObject,43);
end;
//TypInfo.pas Method
SubComp := GetObjectProp(MyComp,'MySubComponent');
if Assigned(SubComp) then
begin
SetPropValue(SubComp,'Prop1',5);
prop1Value := GetPropValue(SubComp,'Prop1');
end;
end;
TypInfo.pas方法仅适用于已发布的属性,您可以使用RTTI获取公共属性.pas方法。
The TypInfo.pas method will only work with published properties, you can get the public properties with the RTTI.pas method.
这篇关于获取/设置使用RTTI的子属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!