c#字典复制值而不是引用

c#字典复制值而不是引用,c#,dictionary,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

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

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);

克隆数组应该是可行的,因为
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());
String[]table=新字符串[3];
表[0]=“x”
表[1]=“x”
表[2]=“x”
Dictionary dict=新字典();
dict.Add(“sth”,(string[])table.Clone();
表[0]=“y”
表[1]=“y”
表[2]=“y”
dict.Add(“sth2”,(string[])table.Clone();

对于您的特定示例,您可能需要在添加时复制数组

dict.Add("sth",table.ToArray());
如果您需要不变性和性能(因为复制并不是真正有效的方法),请查看,特别是

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