gpt4 book ai didi

delphi - 使用 Generics.Collections.TObjectDictionary 的示例

转载 作者:行者123 更新时间:2023-12-03 14:35:08 27 4
gpt4 key购买 nike

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 的唯一区别是构造函数中指定的键和/或值的所有权,因此相同的概念适用于两者)

关于delphi - 使用 Generics.Collections.TObjectDictionary 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8463968/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com