为Dictionary Array指定值会覆盖现有值

时间:2013-03-04 07:20:00

标签: c# .net

我的代码如下:

Dictionary<string, string>[] Records = new Dictionary<string, string>[2];         
Dictionary<string, string> newFields = new Dictionary<string, string>();

newFields["Item"] = "M1";
newFields["Value"] = "V1";

Records[0] = newFields;

newFields["Item"] = "M2"; // This also changes values in Records[0]
newFields["Value"] = "V2";

Records[1] = newFields;

但是一旦我再次分配newFields,它也会更改Records [0]中的值????????????????

2 个答案:

答案 0 :(得分:4)

这是因为您将newFields的引用分配给Records[0]

试试这个:

/* .... */

Records[0] = new Dictionary<string, string>(newFields);

/* .... */

答案 1 :(得分:3)

Records[0] = newFields;传递引用,而不是该字典的副本。这就是为什么Records[0]newFields指向同一个对象的原因。

要制作现有Dictionary实例的副本,请使用:

Records[0] = new Dictionary<string, string>(newFields);