Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Delphi 如何添加到通用TList<;价值,t词典>;在德尔菲_Delphi - Fatal编程技术网

Delphi 如何添加到通用TList<;价值,t词典>;在德尔菲

Delphi 如何添加到通用TList<;价值,t词典>;在德尔菲,delphi,Delphi,我试图使用对象的通用字典,其中它们的键是字符串,值是TDictionary。这可能吗?我不明白为什么不能,但我不知道要添加到字典中的语法是什么。我试过几件事,但都做不好。也许必须以某种方式使用TPair 这段代码演示了我要做的事情(它没有编译,AddOrSetValue中没有足够的参数) 程序测试; {$APPTYPE控制台} 使用 SysUtils,泛型。集合; 类型 TLookup=t词典; TCache=t词典; 变量 Cache:TCache; 开始 Cache:=TCache.Crea

我试图使用对象的通用字典,其中它们的键是字符串,值是TDictionary。这可能吗?我不明白为什么不能,但我不知道要添加到字典中的语法是什么。我试过几件事,但都做不好。也许必须以某种方式使用TPair

这段代码演示了我要做的事情(它没有编译,AddOrSetValue中没有足够的参数)

程序测试;
{$APPTYPE控制台}
使用
SysUtils,泛型。集合;
类型
TLookup=t词典;
TCache=t词典;
变量
Cache:TCache;
开始
Cache:=TCache.Create;
尝试
AddOrSetValue['Hi',([1,2]);
最后
缓存。免费;
结束;
结束。

如果您的值是字典,则Cache.Add的第二个参数必须是字典。因此:

Cache.AddOrSetValue('Hi', TLookup.Create);
Cache['Hi'].AddOrSetValue(1, 2);
但是,当值是对象时,请小心使用AddOrSetValue。如果不小心,可能会导致内存泄漏。

尝试以下方法:

program DictTest; 

{$APPTYPE CONSOLE} 

uses 
  SysUtils, Generics.Collections; 

type 
  TLookup = TDictionary<integer, integer>; 
  TCache = TDictionary<string, TLookup>; 

var 
  Cache : TCache; 
  ALookup: TLookup;
begin 
  Cache := TCache.Create; 
  try 
    ALookup := TLookup.Create;
    ALookup.Add(1, 2);
    Cache.AddOrSetValue['Hi', ALookup]; 
  finally 
    Cache.Free; 
  end; 
end. 
程序测试;
{$APPTYPE控制台}
使用
SysUtils,泛型。集合;
类型
TLookup=t词典;
TCache=t词典;
变量
Cache:TCache;
阿洛库普:特卢库普;
开始
Cache:=TCache.Create;
尝试
ALookup:=TLookup.Create;
添加(1,2);
Cache.AddOrSetValue['Hi',ALookup];
最后
缓存。免费;
结束;
结束。
program DictTest; 

{$APPTYPE CONSOLE} 

uses 
  SysUtils, Generics.Collections; 

type 
  TLookup = TDictionary<integer, integer>; 
  TCache = TDictionary<string, TLookup>; 

var 
  Cache : TCache; 
  ALookup: TLookup;
begin 
  Cache := TCache.Create; 
  try 
    ALookup := TLookup.Create;
    ALookup.Add(1, 2);
    Cache.AddOrSetValue['Hi', ALookup]; 
  finally 
    Cache.Free; 
  end; 
end.