Delphi 访问字典项

Delphi 访问字典项,delphi,tdictionary,Delphi,Tdictionary,我正在使用embarcadero样本测试TDictionary( ) 创建和添加键和值没有问题。但是,当我尝试使用键值“London”访问表时: (1) Dictionary.Items['London'].Country->给出正确的值“Dictionary.Items['London'].Country” (2) 在Edit1.Text中输入'London',然后 Dictionary.Items[Edit1.Text].Country->给出错误“找不到项” 有人能解释一下吗 提前谢谢 /

我正在使用embarcadero样本测试TDictionary( )

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

(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;
var字典:t字典;
城市,价值:城市;
键:字符串;
开始
字典:=t字典。创建;
城市:=TCity.Create;
{将一些键值对添加到字典。}
城市.国家:='罗马尼亚';
城市纬度:=47.16;
城市经度:=27.58;
添加('Iasi',城市);
城市:=TCity.Create;
城市。国家:=‘英国’;
城市纬度:=51.5;
城市经度:=-0.17;
加上(‘伦敦’、城市);
城市:=TCity.Create;
城市。国家:=‘阿根廷’;
{注意错误的坐标}
城市纬度:=0;
城市经度:=0;
字典。添加(‘布宜诺斯艾利斯’,城市);
showmessage(Dictionary.Items['London'].Country);//这个没问题
//现在使用Edit1.Text,我在其中放置“伦敦”
Showmessage(Dictionary.Items[Edit1.Text].Country);//此返回错误消息(未找到项)
字典。清晰;
字典。免费;
城市。免费;
结束;

解释是,与您声称的相反,
Edit1.Text
不等于
“伦敦”
。也许字母大小写不匹配。或者存在前导或尾随空格

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

Assert(Edit1.Text='London');

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