遍历字典时不能修改字典的内容

private GtsActor(IDictionary<string, double> configs)
{   
foreach(var kv in this.configs)   {   if (configs.ContainsKey(kv.Key))   this.configs[kv.Key] = configs[kv.Key]; }
}

Exception: 集合已修改;可能无法执行枚举操作。

   在 System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   在 System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()

 

如果确实存在需要先确认字典是否存在指定键,然后修改怎么办?很简单,改变遍历源,直接修改目标。这样在语义上也更加正确一些。

private GtsActor(IDictionary<string, double> configs)
 {
            foreach(var kv in configs)
            {
                if (this.configs.ContainsKey(kv.Key))
                    this.configs[kv.Key] = configs[kv.Key];
            }

 }

 

posted @ 2016-07-25 09:55  jjseen  阅读(344)  评论(0编辑  收藏  举报