c#Dictionary复制值而不是引用

时间:2015-07-25 16:01:30

标签: c# dictionary

我们都知道在这种情况下:

String[] table= new String[3];
table[0] = "x"
table[1] = "x"
table[2] = "x"
Dictionary<string, String[]> dict = new Dictionary<string, String[]>();
dict.Add("sth",table);
table[0] = "y"
table[1] = "y"
table[2] = "y"
dict.Add("sth2",table);

我会获得不同的密钥,但值yyy相同,因为我们在dict.Add()提供了参考。有没有办法给出一个参考而不是一个值,f.e。得到:

<"sth",{x,x,x}>
<"sth",{y,y,y}>

2 个答案:

答案 0 :(得分:2)

克隆数组应该有效,因为string应该是不可变的。

String[] table = new String[3];

table[0] = "x"
table[1] = "x"
table[2] = "x"

Dictionary<string, String[]> dict = new Dictionary<string, String[]>();

dict.Add("sth", (string[])table.Clone());

table[0] = "y"
table[1] = "y"
table[2] = "y"

dict.Add("sth2", (string[])table.Clone());

答案 1 :(得分:1)

对于您的具体示例,您可能需要在添加时复制数组。

dict.Add("sth",table.ToArray());

如果你需要不变性和性能(因为复制不是真正有效的方法) - 请Immutable Collections,特别是ImmutableList