首页 > 解决方案 > 在空字典Delphi 10.4上迭代的问题

问题描述

我有以下带有两个字典的代码。我可以看到,当我遍历 DictForbidden 时,即使它是空的,执行流程也会进入循环,所以 DictToAdd.remove(anInteger); 使用 anInteger 的旧值执行

var DictForbidden, DictToAdd : TDictionary<Integer,boolean>; 
var anInteger: Integer;
    
DictForbidden   := TDictionary<Integer,boolean>.Create;
DictToAdd       := TDictionary<Integer,boolean>.Create;
    
anInteger := 1;
DictToAdd.Add(anInteger,true);
    
for anInteger in DictForbidden.Keys do
  DictToAdd.remove(anInteger);
    
DictForbidden.Free;
DictToAdd.Free; 

我正在运行 Delphi 10.4,但我不记得在 10.3 中有这样的行为。我想当时如果字典为空,则没有输入循环。你知道这是否是 Delphi 10.4 上的新东西吗?或者我在这里做错了什么?

问候,卡洛斯

标签: dictionarydelphiiteration

解决方案


在我的 10.4.1 中它没有进入循环。但是由于编译器进行了优化,当您调试跟踪时,它可能看起来像这样。尝试更换

DictToAdd.Remove

writeln(anInteger) // if Console Application
ShowMessage(IntToStr(anInteger)) // if GUI Application

看看是否有任何报告。


推荐阅读