2011-12-11 52 views
13

Delphi XE2のオンラインヘルプ(およびEmbarcadero DocWiki)は、TObjectDictionaryのドキュメントでは非常に薄いです(または私はそれを見つけるのが馬鹿です)。Generics.Collections.TObjectDictionaryの使用例

私が理解する限り、それは文字列キー(基本的に常にソートされたTStringListではありえますが、タイプセーフであったもの)でアクセスできるオブジェクトインスタンスを格納するために使用できます。しかし、私は実際にそれを宣言して使用する方法を失っています。

任意のポインタ?

+0

TDictionaryまたはTObjectDictionaryのキーは文字列である必要はありません。それらはどんなタイプでもかまいません。 TObjectDictionaryの* values *はTObjectを拡張する必要がありますが、TDictionaryは任意の型の値を格納できます。 – awmross

答えて

24

TObjectDictionaryTDictionaryの主な違いは、コレクション(辞書)に追加されたキーや値の所有権を指定するメカニズムを提供することです。したがって、これらのオブジェクトを解放することについて心配する必要はありません。

チェックこの基本的なサンプルを

{$APPTYPE CONSOLE}  
{$R *.res} 
uses 
    Generics.Collections, 
    Classes, 
    System.SysUtils; 


Var 
    MyDict : TObjectDictionary<String, TStringList>; 
    Sl  : TStringList; 
begin 
    ReportMemoryLeaksOnShutdown:=True; 
    try 
    //here i'm creating a TObjectDictionary with the Ownership of the Values 
    //because in this case the values are TStringList 
    MyDict := TObjectDictionary<String, TStringList>.Create([doOwnsValues]); 
    try 
    //create an instance of the object to add 
    Sl:=TStringList.Create; 
    //fill some foo data 
    Sl.Add('Foo 1'); 
    Sl.Add('Foo 2'); 
    Sl.Add('Foo 3'); 
    //Add to dictionary 
    MyDict.Add('1',Sl); 

    //add another stringlist on the fly 
    MyDict.Add('2',TStringList.Create); 
    //get an instance to the created TStringList 
    //and fill some data 
    MyDict.Items['2'].Add('Line 1'); 
    MyDict.Items['2'].Add('Line 2'); 
    MyDict.Items['2'].Add('Line 3'); 


    //finally show the stored data 
    Writeln(MyDict.Items['1'].Text); 
    Writeln(MyDict.Items['2'].Text);   
    finally 
    //only must free the dictionary and don't need to worry for free the TStringList assignated to the dictionary 
    MyDict.Free; 
    end; 
    except 
    on E: Exception do 
     Writeln(E.ClassName, ': ', E.Message); 
    end; 
    Readln; 
end. 

TObjectDictionaryとの唯一の違いは、指定されたキーおよび/または値の所有であることを覚えている(TDictionaryを使用する方法についての完全なサンプルのために、このリンクGenerics Collections TDictionary (Delphi)をチェック同じコンセプトが両方に適用されます)

+6

+1キーの扱いを同様にするには 'doOwnsKeys'を使います –