在不知道 属性 是什么类型的情况下使用 RTTI 分配属性
Assigning properties using RTTI without knowing what type the property is
我有一些属性未知的对象 newObject
,我希望能够在不知道 属性 是什么类型的情况下为其属性赋值。
到目前为止我能做的最好的是
vCtx := TRttiContext.Create;
vType := vCtx.GetType(newObject.ClassType);
for vProp in vType.GetProperties do
begin
vPropValue := 'Test Value';
val := TValue.From<String>( vPropValue);
vProp.SetValue( newObject , val );
end;
当然,这是假设属性的类型是string
如何使它更通用?
因为你没有提供从哪里获得价值的信息,并说你可以自己处理(在评论中)我只是 post 找出 属性 的部分除非您提供额外的信息,否则请输入并把剩下的留给您。
其他的类型我也留给你,给你一个大概的概念。
if vProp.IsWritable then
begin
case vProp.PropertyType.TypeKind of
tkInteger: val := TValue.From<Integer>(...);
tkFloat: val := TValue.From<Double>(...);
tkUString: val := TValue.From<string>(...);
end;
vProp.SetValue(newObject, val);
end;
我有一些属性未知的对象 newObject
,我希望能够在不知道 属性 是什么类型的情况下为其属性赋值。
到目前为止我能做的最好的是
vCtx := TRttiContext.Create;
vType := vCtx.GetType(newObject.ClassType);
for vProp in vType.GetProperties do
begin
vPropValue := 'Test Value';
val := TValue.From<String>( vPropValue);
vProp.SetValue( newObject , val );
end;
当然,这是假设属性的类型是string
如何使它更通用?
因为你没有提供从哪里获得价值的信息,并说你可以自己处理(在评论中)我只是 post 找出 属性 的部分除非您提供额外的信息,否则请输入并把剩下的留给您。
其他的类型我也留给你,给你一个大概的概念。
if vProp.IsWritable then
begin
case vProp.PropertyType.TypeKind of
tkInteger: val := TValue.From<Integer>(...);
tkFloat: val := TValue.From<Double>(...);
tkUString: val := TValue.From<string>(...);
end;
vProp.SetValue(newObject, val);
end;