2011-12-11 8 views
13

La guida in linea di Delphi XE2 (così come l'Embarcadero DocWiki) è molto sottile sulla documentazione di TObjectDictionary (o sono troppo stupido per trovarlo).Esempio per l'utilizzo di Generics.Collections.TObjectDictionary

Per quanto ho capito, può essere utilizzato per memorizzare istanze di oggetti a cui è possibile accedere tramite chiavi di stringa (in pratica ciò che era sempre possibile con un TStringList ordinato ma typesafe). Ma non so come effettivamente dichiararlo e usarlo.

Eventuali suggerimenti?

+0

Le chiavi in ​​TDictionary o TObjectDictionary non devono essere stringhe. Possono essere di qualsiasi tipo. I valori * in un TObjectDictionary devono estendere TObject, mentre TDictionary può memorizzare valori di qualsiasi tipo. – awmross

risposta

24

La differenza principale tra un TObjectDictionary e TDictionary è che fornisce un meccanismo per specificare la proprietà delle chiavi e/o valori aggiunti alla collezione (dizionario), quindi non c'è bisogno di preoccuparsi di liberare questi oggetti.

controllare questo campione di base

{$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. 

controllare questo link Generics Collections TDictionary (Delphi) per un campione completo su come utilizzare un TDictionary (ricordate l'unica differenza con il TObjectDictionary è la proprietà delle chiavi e/o valori che è specificato nel costruttore, Quindi gli stessi concetti valgono per entrambi)

+6

+1 Usa 'doOwnsKeys' se vuoi un trattamento simile per le chiavi –