-1

我有以下代码:

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] 中的值??????????????

4

2 回答 2

4

这是因为您引用了newFieldsto Records[0]

试试这个:

/* .... */

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

/* .... */
于 2013-03-04T07:22:13.593 回答
3

Records[0] = newFields;传递参考,而不是该字典的副本。这就是为什么两者都Records[0]指向newFields同一个对象。

要复制现有Dictionary实例,请使用:

Records[0] = new Dictionary<string, string>(newFields);
于 2013-03-04T07:22:30.100 回答