Delphi TDictionary迭代

bob*_*ski 18 delphi iteration tdictionary

我有一个函数,我存储一些键值对,当我迭代它们时,我得到两次错误:[dcc32错误] App.pas(137):E2149类没有默认属性.这是我的代码的一部分:

function BuildString: string;
var
  i: Integer;
  requestContent: TDictionary<string, string>;
  request: TStringBuilder;
begin
  requestContent := TDictionary<string, string>.Create();

  try
    // add some key-value pairs
    request :=  TStringBuilder.Create;
    try
      for i := 0 to requestContent.Count - 1 do
      begin
        // here I get the errors
        request.Append(requestContent.Keys[i] + '=' +
          TIdURI.URLEncode(requestContent.Values[i]) + '&');
      end;

      Result := request.ToString;
      Result := Result.Substring(0, Result.Length - 1); //remove the last '&'
    finally
      request.Free;
    end; 
  finally
    requestContent.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

我需要收集字典中每个项目的信息.我该如何解决?

Dav*_*nan 35

KeysValues你的字典类的属性类型TDictionary<string, string>.TKeyCollectionTDictionary<string, string>.TValueCollection分别.这些类是从TEnumerable<T>索引派生的,不能通过索引迭代.然而Keys,您可以迭代,或者实际上Values,不会因为后者对您有用.

如果你迭代Keys你的代码可能看起来像这样:

var
  Key: string;
....
for Key in requestContent.Keys do
  request.Append(Key + '=' + TIdURI.URLEncode(requestContent[Key]) + '&');
Run Code Online (Sandbox Code Playgroud)

然而,这是低效的.既然你知道你想要键和匹配值,你可以使用字典的迭代器:

var 
  Item: TPair<string, string>; 
....
for Item in requestContent do 
  request.Append(Item.Key + '=' + TIdURI.URLEncode(Item.Value) + '&');
Run Code Online (Sandbox Code Playgroud)

对迭代器比上面的第一个变量更有效.这是因为实现细节意味着对迭代器能够迭代字典而不需要:

  1. 计算每个密钥的哈希码,和
  2. 当哈希码发生冲突时执行线性探测.