【问题标题】:Access TDictionary item访问字典项
【发布时间】:2014-02-24 19:34:50
【问题描述】:

我正在使用 embarcadero 样本测试 TDictionary ( http://docwiki.embarcadero.com/CodeExamples/XE5/en/Generics_Collections_TDictionary_%28Delphi%29 )

创建和添加键和值没有问题。但是,当我尝试使用键值“伦敦”访问表时:

(1) Dictionary.Items['London'].Country -> 给出正确的值 "Dictionary.Items['London'].Country'

(2) 在 Edit1.Text 中输入“London”,然后 Dictionary.Items[Edit1.Text].Country -> 给出错误“找不到项目”?

有人能解释一下吗?

提前致谢。

/////////////////////////////// /// 示例代码

var Dictionary: TDictionary<String, TCity>;
    City, Value: TCity;
    Key: String;


begin
  Dictionary := TDictionary<String, TCity>.Create;
  City := TCity.Create;
  { Add some key-value pairs to the dictionary. }
  City.Country := 'Romania';
  City.Latitude := 47.16;
  City.Longitude := 27.58;
  Dictionary.Add('Iasi', City);

  City := TCity.Create;
  City.Country := 'United Kingdom';
  City.Latitude := 51.5;
  City.Longitude := -0.17;
  Dictionary.Add('London', City);

  City := TCity.Create;
  City.Country := 'Argentina';
  { Notice the wrong coordinates }
  City.Latitude := 0;
  City.Longitude := 0;
  Dictionary.Add('Buenos Aires', City);

  showmessage(Dictionary.Items['London'].Country); // This One is OK

  // now using Edit1.Text where I put 'London'
  Showmessage(Dictionary.Items[Edit1.Text].Country); // This return to error message (Item not found)


  Dictionary.Clear;
  Dictionary.Free;
  City.Free;

end;

【问题讨论】:

  • 请记住,以字符串为键的 TDictionary 区分大小写 - 因此,如果您的 Edit1.Text 是 london,它将找不到该项目。
  • 谢谢!在我陷入另一个简单的错误之前,很高兴知道这一点。

标签: delphi tdictionary


【解决方案1】:

解释是,与您声称的相反,Edit1.Text 不等于 'London'。也许字母大小写不匹配。或者有前导或尾随空格。

添加断言以验证我是否正确:

Assert(Edit1.Text='London');

【讨论】:

  • 是的,你是对的。我应该修剪文字!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 2012-05-09
  • 1970-01-01
  • 2019-04-11
  • 2020-01-09
相关资源
最近更新 更多