delphi – 使用Genericics.Collections.TObjectDictionary的示例
发布时间:2020-12-15 10:08:35 所属栏目:大数据 来源:网络整理
导读:Delphi XE2在线帮助(以及Embarcadero DocWiki)在TObjectDictionary的文档中非常薄(或者我太愚蠢地找不到). 据我所知,它可以用于存储可以通过字符串键访问的对象实例(基本上是使用排序的TStringList但是类型安全的).但是我如何实际申报和使用它是一个失败. 任
|
Delphi XE2在线帮助(以及Embarcadero DocWiki)在TObjectDictionary的文档中非常薄(或者我太愚蠢地找不到).
据我所知,它可以用于存储可以通过字符串键访问的对象实例(基本上是使用排序的TStringList但是类型安全的).但是我如何实际申报和使用它是一个失败. 任何指针? 解决方法TObjectDictionary和
TDictionary之间的主要区别在于提供了一种机制来指定添加到集合(字典)中的键和/或值的所有权.因此,您不必担心释放这些对象.
检查这个基本样本 {$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的唯一区别是构造函数中指定的键和/或值的所有权,因此相同的概念适用于两者) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
