Delphi 使用Generics.Collections.TObjectDictionary的示例
Delphi XE2在线帮助(以及Embarcadero DocWiki)在Delphi 使用Generics.Collections.TObjectDictionary的示例,delphi,delphi-xe2,Delphi,Delphi Xe2,Delphi XE2在线帮助(以及Embarcadero DocWiki)在TObjectDictionary的文档中非常少(或者我太笨了,找不到它) 据我所知,它可以用来存储可以通过字符串键访问的对象实例(基本上,排序的TStringList但类型安全的对象实例总是可能的)。但我不知道如何实际申报和使用它 有指针吗?a和a之间的主要区别在于,它提供了一种机制来指定添加到集合(字典)中的键和/或值的所有权,因此您无需担心释放这些对象 检查这个基本样品 {$APPTYPE CONSOLE}
TObjectDictionary
的文档中非常少(或者我太笨了,找不到它)
据我所知,它可以用来存储可以通过字符串键访问的对象实例(基本上,排序的TStringList
但类型安全的对象实例总是可能的)。但我不知道如何实际申报和使用它
有指针吗?a和a之间的主要区别在于,它提供了一种机制来指定添加到集合(字典)中的键和/或值的所有权,因此您无需担心释放这些对象 检查这个基本样品
{$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.
{$APPTYPE控制台}
{$R*.res}
使用
非专利药,收藏,
班级,
System.SysUtils;
变量
MyDict:TObjectDictionary;
Sl:TStringList;
开始
ReportMemoryLeaksOnShutdown:=True;
尝试
//在这里,我创建了一个具有值所有权的TObjectDictionary
//因为在这种情况下,值是TStringList
MyDict:=TObjectDictionary.Create([DoownsValue]);
尝试
//创建要添加的对象的实例
Sl:=TStringList.Create;
//填充一些foo数据
Sl.Add(“Foo 1”);
Sl.Add(“Foo 2”);
Sl.Add(“Foo 3”);
//添加到字典
MyDict.Add('1',Sl);
//动态添加另一个stringlist
MyDict.Add('2',TStringList.Create);
//获取创建的TStringList的实例
//并填写一些数据
MyDict.项目['2'].添加(“第1行”);
MyDict.项目['2'].添加(“第2行”);
MyDict.项目['2'].添加(“第3行”);
//最后显示存储的数据
Writeln(MyDict.Items['1'].Text);
Writeln(MyDict.Items['2'].Text);
最后
//只需释放字典,无需担心分配给字典的TStringList
MyDict.Free;
结束;
除了
关于E:Exception-do
Writeln(E.ClassName,“:”,E.Message);
结束;
Readln;
结束。
查看此链接以获取有关如何使用
t字典的完整示例(请记住,TObjectDictionary与TObjectDictionary的唯一区别在于构造函数中指定的键和/或值的所有权,因此相同的概念适用于这两者)+1使用doOwnsKeys
如果您希望对按键进行类似处理,则StringLis
t对象S1
只有在这是非ARC应用程序时才会被释放。但是,如果应用程序正在使用自动引用计数,StringList
对象在从字典中删除后不会被销毁,因为变量S1仍然在引用它。因此,只有在变量S1超出范围后,对象才会被销毁,在本例中,变量S1在应用程序终止时,因为S1
被声明为全局变量。TDictionary或TObjectDictionary中的键不必是字符串。它们可以是任何类型。TObjectDictionary中的值必须扩展到TObject,而TDictionary可以存储任何类型的值。