首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Delphi TDictionary迭代

Delphi TDictionary迭代
EN

Stack Overflow用户
提问于 2014-09-29 20:22:56
回答 1查看 30.9K关注 0票数 20

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

代码语言:javascript
复制
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;

我需要从字典中的每个条目中收集信息。我怎么才能修复它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-29 20:32:42

字典类的KeysValues属性分别属于TDictionary<string, string>.TKeyCollectionTDictionary<string, string>.TValueCollection类型。这些类是从TEnumerable<T>派生的,不能通过索引进行迭代。但是,您可以在Keys上迭代,或者实际上在Values上迭代,这样做后一种方法对您没有多大用处。

如果您在Keys上迭代,您的代码可能如下所示:

代码语言:javascript
复制
var
  Key: string;
....
for Key in requestContent.Keys do
  request.Append(Key + '=' + TIdURI.URLEncode(requestContent[Key]) + '&');

然而,这是低效的。因为您知道需要键和匹配值,所以可以使用字典的迭代器:

代码语言:javascript
复制
var 
  Item: TPair<string, string>; 
....
for Item in requestContent do 
  request.Append(Item.Key + '=' + TIdURI.URLEncode(Item.Value) + '&');

成对迭代器比上面的第一个变种更有效。这是因为实现细节意味着配对迭代器能够在以下情况下迭代字典:

and

  • Performing
  1. 计算每个键的散列码,当散列码发生冲突时进行线性探测。
票数 44
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26099848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档