La principal diferencia entre TObjectDictionary
y TDictionary
es que proporciona un mecanismo para especificar la propiedad de las claves y/o valores agregados a la colección (diccionario), por lo que no tiene que preocuparse de liberar estos objetos.
Marque esta muestra básica
{$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.
Comprobar este enlace Generics Collections TDictionary (Delphi) para una muestra completa acerca de cómo utilizar un TDictionary
(Recuerde que la única diferencia con el TObjectDictionary es la propiedad de las teclas y/o los valores que se especifican en el constructor, entonces los mismos conceptos se aplican a ambos)
Las claves en un TDictionary o TObjectDictionary no tienen que ser cadenas. Pueden ser de cualquier tipo. Los * valores * en un TObjectDictionary deben extender TObject, mientras que TDictionary puede almacenar valores de cualquier tipo. – awmross