Delphi 2010中的rtti数据操作和一致性 [英] Rtti data manipulation and consistency in Delphi 2010

查看:106
本文介绍了Delphi 2010中的rtti数据操作和一致性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道吗,如何使用对原始数据的引用来创建TValue?在我的序列化项目中,我使用(如 XML-Serialization中所建议)是一种通用序列化程序,它将TValues存储在内部树结构中(类似于示例中的MemberMap).

Has anyone an idea, how I can make TValue using a reference to the original data? In my serialization project, I use (as suggested in XML-Serialization) a generic serializer which stores TValues in an internal tree-structure (similar to the MemberMap in the example).

此成员树还应用于创建动态设置表单并处理数据. 我的想法是为数据定义一个属性:

This member-tree should also be used to create a dynamic setup form and manipulate the data. My idea was to define a property for the Data:

TDataModel <T> = class
  {...}
  private
    FData : TValue;
    function GetData : T;
    procedure SetData (Value : T);
  public
    property Data : T read GetData write SetData;
end;

GetData,SetData方法的实现:

The implementation of the GetData, SetData Methods:

procedure TDataModel <T>.SetData (Value : T);

begin
FData := TValue.From <T> (Value);
end;

procedure TDataModel <T>.GetData : T;

begin
Result := FData.AsType <T>;
end;

不幸的是,TValue.From方法始终会复制原始数据.因此,每当应用程序对数据进行更改时,DataModel都不会更新,反之亦然,如果我以动态形式更改DataModel,原始数据也不会受到影响. 当然,在更改任何东西之前和之后,我总是可以使用Data属性,但是由于我在DataModel中使用了很多Rtti,所以我真的不想在任何时候这样做.

Unfortunately, the TValue.From method always makes a copy of the original data. So whenever the application makes changes to the data, the DataModel is not updated and vice versa if I change my DataModel in a dynamic form, the original data is not affected. Sure I could always use the Data property before and after changing anything, but as I use lot of Rtti inside my DataModel, I do not realy want to do this anytime.

也许有人有更好的建议?

Perhaps someone has a better suggestion?

推荐答案

TValue旨在以非常紧凑的形式保存任何类型的数据,而并非旨在模拟指针".看一下RTTI.pas单元:TValue是一个RECORD,只有一个TValueData类型的数据成员. TValueData本身本身就是一个变体记录.

A TValue is designed to hold any kind of data in a very compact form, it's not designed to emulate an "pointer". Take a look in the RTTI.pas unit: TValue is a RECORD that only has one data member of the type TValueData. TValueData itself is itself a variant record.

查看TValueData,您将看到它除了最小的数据量外什么都不保存:没有办法知道TValue的来源.

Looking at TValueData you will see how it does NOT hold anything but the minimum amount of data: There's no way to know where that TValue came from.

解决方案:不要在您的结构中持有TValue,而是将其替换为一对TRttiField +一个TObject.当您需要TValue时,请使用TRttiField.GetValue(Instance),当您要设置值时,请使用TRttiField.SetValue(Instance,AValue:TValue).

The solution: Don't hold a TValue in your structures, replace it with a pair of TRttiField + an TObject. When you need the TValue use TRttiField.GetValue(Instance), when you want to set a value use TRttiField.SetValue(Instance, AValue:TValue).

这篇关于Delphi 2010中的rtti数据操作和一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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