本文介绍了Delphi 2010 RTTI:使用TValue存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用TValue将数据存储在TList中.就像在:

I would like to be able to use TValue to store Data in a TList<>. Like in :

type
  TXmlBuilder = class
  type
    TXmlAttribute = class
      Name: String;
      Value: TValue; // TValue comes from Rtti
    end;

    TXmlNode = class
      Name: String;
      Parent: TXmlNode;
      Value: TXmlNode;
      Attributes: TList<TXmlAttribute>;
      Nodes: TList<TXmlNode>;
      function AsString(Indent: Integer): String;
    end;
  ...
  public
    ...
    function N(const Name: String): TXmlBuilder;
    function V(const Value: String): TXmlBuilder;
    function A(const Name: String; Value: TValue): TXmlBuilder; overload;
    function A<T>(const Name: String; Value: T): TXmlBuilder; overload;
    ...
 end;

implementation

function TXmlBuilder.A(const Name: String; Value: TValue): TXmlBuilder;
var
  A: TXmlAttribute;
begin
  A := TXmlAttribute.Create;
  A.Name := Name;
  A.Value := Value;
  FCurrent.Attributes.Add(A);
  Result := Self;
end;

function TXmlBuilder.A<T>(const Name: String; Value: T): TXmlBuilder;
var
  V: TValue;
begin
  V := TValue.From<T>(Value);
  A(Name, V);
end;

稍后,在主程序中,我使用这样的流利" xml构建器:

And a bit later, in the main program, I use my "fluent" xml builder like this :

b := TXmlBuilder.Create('root');
b.A('attribute', 1).A('other_attribute', 2).A<TDateTime>('third_attribute', Now);

在第二次调用时,程序引发访问冲突异常.

On the second call, the program raises an access violation exception.

第一个TValue似乎已释放".真的可以使用TValue在运行时存储变量"数据吗?

It looks like the first TValue has been "freed". Is it really possible to use TValue to store "Variant" data a runtime ?

我知道Delphi中存在Variants.我的XML构建器将用于使用RTTI将本地delphi对象反序列化为XML,因此我将在所有地方都使用TValue.

I know that Variants exists in Delphi. My XML builder will be used to (de)serialize native delphi objects to XML using RTTI so I will be using TValue everywhere.

致谢

-皮埃尔·雅格

推荐答案

我找到了答案.我的错.

I found the answer. My mistake.

function TXmlBuilder.A<T>(const Name: String; Value: T): TXmlBuilder;
var
  V: TValue;
begin
  V := TValue.From<T>(Value);
  Result := A(Name, V); // I missed the return value
end;

抱歉;-)

这篇关于Delphi 2010 RTTI:使用TValue存储数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-07 20:11