使用Generics.Collections.TObjectDictionary的例子

19

Delphi XE2在线帮助文档以及Embarcadero DocWiki在的文档中非常匮乏(或者我太蠢找不到)。

据我所知,它可以用于存储可以通过字符串键访问的对象实例(基本上是一直可以使用的已排序的但是类型安全)。但我不知道如何声明和使用它。

有任何指针吗?


TDictionary或TObjectDictionary中的键不必是字符串,可以是任何类型。TObjectDictionary中的必须扩展自TObject,而TDictionary可以存储任何类型的值。 - awmross
1个回答

31
主要区别在于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.

请查看此链接Generics Collections TDictionary (Delphi),其中提供了完整的示例,说明如何使用TDictionary(请记住,与TObjectDictionary唯一的区别在于构造函数中指定了键和/或值的所有权,因此相同的概念适用于两者)。

8
如果您想对键值进行类似的处理,请使用doOwnsKeys - David Heffernan
1
如果这是一个非 ARC 应用程序,StringList 对象 S1 将被释放。但是,如果您的应用程序使用自动引用计数,则在从字典中删除 StringList 对象后,该对象不会被销毁,因为您的变量 S1 仍然引用它。因此,在变量 S1 超出范围之后,该对象将被销毁,例如在应用程序终止时,因为 S1 被声明为全局变量。 - SilverWarior

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接