3

我在一个窗口中有一个应用程序级别变量

  object temp1 = App.Current.Properties["listofstring"];

   var temp2 = (List<string>)temp1;

当我改变时让我们说

 temp2[0]="abc";

它也改变了“listofstring”

所以我复制了一份

List<string> temp3 = temp2;

但如果我这样做

 temp3[0] ="abc"; 

在其他窗口中访问时,它也会在“listofstring”中发生变化吗?

一旦声明,我如何只使用它的本地副本而不干扰其内容?

4

1 回答 1

5

您不是在复制列表,而是在复制参考。你可以做:

List<string> temp3 = new List<string>(temp2.ToArray());
//or
List<string> temp3 = new List<string>(temp2);

或者

List<string> temp3 = temp2.Select(r=>r).ToList();
//or 
List<string> temp3 = temp2.ToList();
于 2013-03-06T12:56:18.087 回答