我有一個Dictionary<string, IEnumerable<string>>
類型的字典和一個字符串值列表。出於某種原因,每次我進行添加時,字典中的每個值都會被覆蓋。至於爲什麼會發生這種情況,我完全被難住了。我確信,在循環中聲明和初始化IEnumberable對象並不是一個引用問題,因此它的作用域不會超出一個迭代範圍,它仍然會執行此操作。這裏是我的代碼:爲什麼Dictionary.Add會覆蓋我的字典中的所有項目?
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
是我的字典。
你有「關閉了循環變量」。每添加一個'lst'都將使用* last *'type'變量。請閱讀:http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx有趣的是,這個問題將會消失C #5! – dlev 2012-04-23 17:07:19
我一定會閱讀。再次感謝大家的幫助! – Annath 2012-04-23 17:23:56