我将值放入字典时遇到问题。
我的代码:
Dictionary<string, Dictionary<string, int>> cnDict = new Dictionary<string, Dictionary<string, int>>();
Dictionary<string, int> cn = new Dictionary<string,int>();
cn.Add("DynamicPanel_1", 0);
cn.Add("DynamicPanel_3", 1);
cn.Add("DynamicPanel_4", 0);
this.cnDict.Add("DynamicPanel_2", cn);
cn.Clear();
cn.Add("DynamicPanel2", 1);
cn.Add("DynamicPanel3", 0);
this.cnDict.Add("DynamicPanel1", cn);
foreach(KeyValuePair<string, int> pos in cnDict["DynamicPanel_2"])
{
MessageBox.Show("DynamicPanel_2 has values: "+ pos.Key + " ----> " + pos.Value.ToString()); ;
}
foreach (KeyValuePair<string, int> pos in cnDict["DynamicPanel_1"])
{
MessageBox.Show("DynamicPanel_1 has values: " + pos.Key + " ----> " + pos.Value.ToString()); ;
}
此代码显示错误消息:
DynsmicPanel_2的值为:DynamicPanel_3 ----&gt; 0
DynsmicPanel_1的值为:DynamicPanel_2 ----&gt; 1
应该是:
DynsmicPanel_2的值为:DynamicPanel_4 ----&gt; 0
DynsmicPanel_1的值为:DynamicPanel_2 ----&gt; 1
我做错了什么?
由于
答案 0 :(得分:3)
将相同的cn
对象添加两次到cnDict
字典。创建新对象:将cn.Clear();
替换为cn = new Dictionary<string,int>();