我在一个窗口中有一个应用程序级变量
object temp1 = App.Current.Properties["listofstring"];
var temp2 = (List<string>)temp1;
Run Code Online (Sandbox Code Playgroud)
当我改变让我们说
temp2[0]="abc";
Run Code Online (Sandbox Code Playgroud)
它也改变了"listofstring"
所以我复制了一份
List<string> temp3 = temp2;
Run Code Online (Sandbox Code Playgroud)
但如果我这样做
temp3[0] ="abc";
Run Code Online (Sandbox Code Playgroud)
在其他窗口中访问时,它也会在"listofstring"中更改?
我如何只使用它的本地副本一旦声明不打扰其内容?
您没有复制列表,而是复制参考.你可以做:
List<string> temp3 = new List<string>(temp2.ToArray());
//or
List<string> temp3 = new List<string>(temp2);
Run Code Online (Sandbox Code Playgroud)
要么
List<string> temp3 = temp2.Select(r=>r).ToList();
//or
List<string> temp3 = temp2.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
585 次 |
| 最近记录: |