【发布时间】:2014-09-29 12:22:55
【问题描述】:
我有一个存储一些键值对的函数,当我对它们进行迭代时,我得到了两次这个错误:[dcc32 Error] App.pas(137): E2149 Class does not have a default property。 这是我的代码的一部分:
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;
我需要从字典中的每个项目中收集信息。我该如何解决?
【问题讨论】:
-
var S: string; Pair: TPair<string, string>; begin for Pair in YourDictionary do S := Pair.Key + Pair.Value; end; -
使用
for AKey in requestContent.Keys do begin request.Append(AKey + '=' + TIdURI.Encode(requestContent[AKey]) + '&'); ... etc.。当然,您必须将AKey声明为字符串。 -
@RudyVelthuis 使用字典,迭代对比迭代键几乎总是更好。这样做总是会产生更高效的代码。在 Delphi 字典的情况下,pair 迭代器避免了计算哈希码和执行探测的任何需要。
-
@David:我看到了你的回答并 +1 编辑了它。我同意。我首先想到了一个最接近问题的解决方案,但获得对确实更好。
标签: delphi iteration tdictionary