我有一个类型为 Dictionary<string,IEnumerable<string>>
的字典以及一个字符串值的列表。由于某种原因,每次进行添加操作时,字典中的每个值都会被覆盖。我完全不知道为什么会发生这种情况。我确保它不是引用问题,通过在循环中声明和初始化 IEnumberable 对象,使其范围不超出一个迭代范围,并且它仍然发生了这种情况。以下是我的代码:
foreach (string type in typelist)
{
IEnumerable<string> lst =
from row in root.Descendants()
where row.Attribute("serial").Value.Substring(0, 3).Equals(type)
select row.Attribute("serial").Value.Substring(3).ToLower();
serialLists.Add(type, lst);
}
其中typelist
是一个IEnumerable<string>
,root
是一个XElement
,而serialLists
是我的Dictionary
。
lst
时都会使用最后一个type
变量。请阅读此内容:http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx 有趣的是,这个问题在C#5中将消失! - dlev