4

TValueを使用してデータをTList<>に格納できるようにしたいと思います。のように :

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ビルダーを使用します。

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

2回目の呼び出しで、プログラムはアクセス違反の例外を発生させます。

最初のTValueが「解放」されたようです。TValueを使用して「バリアント」データをランタイムに保存することは本当に可能ですか?

Delphiにはバリアントが存在することを知っています。私のXMLビルダーは、RTTIを使用してネイティブのdelphiオブジェクトをXMLに(逆)シリアル化するために使用されるため、どこでもTValueを使用します。

よろしく、

-ピエール・イェーガー

4

1 に答える 1

3

私は答えを見つけました。私の間違い。

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; 

ごめん ;-)

于 2010-01-26T12:04:29.223 に答える