为什么我的字典数据被覆盖了?

Why is my dictionary data being overwritten?

不确定这里发生了什么。当我将数据更新到第二个条目时,我存储在第一个字典条目中的数据项会被覆盖。字典的第一个条目就像使用对原始对象的引用一样,所以当我更改它时,字典中的所有实例都会更改。第一组数据为1,2,3,存放在partitionInfo[0]中。当我要存储下一组数据时,4、5、6 partitionInfo[1] 会更新,但 parttionInfo[0] 也会更新这些值。所以我最终得到我的两个字典条目具有相同的数据集。但是字符串保持唯一。我所看到的表示代码

private void button1_Click(object sender, EventArgs e)
    {
        Datum dataItems = new Datum();
        Partition partitionItem = new Partition();
        LRU lruItem = new LRU();

        dataItems.minData = "1";
        dataItems.maxData = "2";
        dataItems.avgData = "3";
        partitionItem.partitionInfo.Add("Entry1", dataItems);


        dataItems.minData = "4";
        dataItems.maxData = "5";
        dataItems.avgData = "6";
        partitionItem.partitionInfo.Add("Entry2", dataItems);

        lruItem.lruInfo.Add("Parent", partitionItem);

    }


public class LRU
{
    public Dictionary<string, Partition> lruInfo = new Dictionary<string, Partition>();
}

public class Partition
{
  public Dictionary<string, Datum> partitionInfo = new Dictionary<string, Datum>();
}

public class Datum
{
    public string minData;
    public string maxData;
    public string avgData;

}

您正在覆盖以 dataItems.minData = "4"; 行开头的值,仅仅因为您已将值存储在 Entry1 中,它并没有像我怀疑的那样“将其锁定”。

你原来的评论:

The dictionary's first entry is acting like it is using a reference to the original object so when I change it all instances in the dictionary change

您即将掌握代码中的错误...

查看固定代码:

Partition partitionItem = new Partition();

Datum dataItems = new Datum(); 
// **** It's better to declare your variables just
// before you use them to make it clearer ****
dataItems.minData = "1";
dataItems.maxData = "2";
dataItems.avgData = "3";
partitionItem.partitionInfo.Add("Entry1", dataItems);


dataItems = new Datum(); // **** ADDED LINE ****

// We now have a new block of memory containing a `Datum` 
// the one above is left untouched
dataItems.minData = "4";
dataItems.maxData = "5";
dataItems.avgData = "6";
partitionItem.partitionInfo.Add("Entry2", dataItems);

LRU lruItem = new LRU(); **** Moved, as before ****
lruItem.lruInfo.Add("Parent", partitionItem);