Dictionary <string,int =“”>没有值</string,>

时间:2014-04-01 10:23:14

标签: c# dictionary

我将值放入字典时遇到问题。

我的代码:

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_2 ----&gt; 1
  • DynsmicPanel_2的值为:DynamicPanel_3 ----&gt; 0

  • DynsmicPanel_1的值为:DynamicPanel_2 ----&gt; 1

  • DynsmicPanel_1的值为:DynamicPanel_3 ----&gt; 0

应该是:

  • DynsmicPanel_2的值为:DynamicPanel_1 ----&gt; 0
  • DynsmicPanel_2的值为:DynamicPanel_3 ----&gt; 1
  • DynsmicPanel_2的值为:DynamicPanel_4 ----&gt; 0

  • DynsmicPanel_1的值为:DynamicPanel_2 ----&gt; 1

  • DynsmicPanel_1的值为:DynamicPanel_3 ----&gt; 0

我做错了什么?

由于

1 个答案:

答案 0 :(得分:3)

将相同的cn对象添加两次到cnDict字典。创建新对象:将cn.Clear();替换为cn = new Dictionary<string,int>();