Delphi 2010 RTTI : Use TValue to store data

delphi, delphi-2010, rtti, tvalue

Solution

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; 

Sorry ;-)

Problem

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; ``` 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. It looks like the first TValue has been "freed". Is it really possible to use TValue to store "Variant" data a runtime ? 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. regards, -- Pierre Yager

Original source