【问题标题】:Adding Item to Dictionary is breaking foreach loop将项目添加到字典正在破坏 foreach 循环
【发布时间】:2015-01-27 22:58:54
【问题描述】:

我正在尝试遍历一组项目并将它们的属性添加到字典中,但由于某种原因它没有完成循环。

我的代码:

Dictionary<string, Tuple<string, string>> elementList = new Dictionary<string, Tuple<string, string>>(); 
public void AddElementList(AutomationElementCollection collection)
{

    foreach (AutomationElement ele in collection)
    {
        elementList.Add(ele.Cached.Name, new Tuple<string, string>(ele.Cached.LocalizedControlType.ToString(), ele.Cached.AutomationId.ToString()));
        i++;

    }
    MessageBox.Show(i.ToString());
}    

它根本没有进入 MessageBox.Show。通常有大约 52 个项目,它循环通过 8 个然后退出。

【问题讨论】:

  • 在调试器中捕获或中断异常,您可能会看到哪里出错了。可能尝试插入重复的键。
  • 我最好的猜测是ele.Cached.Name 重复,抛出异常。
  • 是的,完全正确,我不敢相信我没想到!
  • 既然你的Tuple 只包含两个值,为什么不使用KeyValuePair? .Net 将比Tuple 提供更好的支持。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# loops dictionary foreach ui-automation


【解决方案1】:

你说它经过 8 次然后停止。当您在字典上调用Add 时,可能会抛出ArgumentException,因为字典中已经存在具有相同键的元素。

发生这种情况是因为当您在字典中查找一个值时,它会查找该键,因为如果有两个相同的键,您将不知道要返回哪个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多