抱歉,如果该主题含糊不清,我会尽可能地总结一下,而不知道要达到的确切术语。
本质上我有一个列表,然后调用一个方法
public List<int> myList;
void Start () {
myList = new List<int>();
myList.Add (1);
myList.Add (2);
doSomething(myList);
foreach (int i in myList){
print (i);
}
}
Run Code Online (Sandbox Code Playgroud)
在我的方法中,我想这样做(例如)
public void doSomething (List<int> myPassedList)
{
int A = 5;
myPassList.Add (A);
//... And then some other cool code with this modified list
}
Run Code Online (Sandbox Code Playgroud)
但是,我不想更改原始列表,我希望它保持原样。本质上,当我将列表传递给方法时,我想要列表的副本,然后在每次调用该方法时将其复制。
我想看到控制台打印“ 1”然后是“ 2”
但会显示“ 1”,“ 2”和“ 5”
希望这一切都有道理!非常感谢您的任何帮助
吉姆
如果您编写了一个处理列表但不会修改该列表的方法,那么您应该通过代码记录这一点
public void doSomething ( IEnumerable<int> myPassedValues )
{
List<int> newList = myPassedValues.ToList();
int A = 5;
newList.Add(A);
//... And then some other cool code with this modified list
}
Run Code Online (Sandbox Code Playgroud)
现在你和所有其他人都会知道,只需阅读此方法中不会修改传递的列表的声明。
List是引用类型,因此当您myPassedList作为参数传递给doSomething您时,您正在修改原始列表。
例如,您有两个选择,要么调用ToList()要么创建一个新列表:
public void doSomething (List<int> myPassedList)
{
List<int> newList = myPassedList.ToList();
int A = 5;
newList.Add(A);
//... And then some other cool code with this modified list
}
Run Code Online (Sandbox Code Playgroud)
这样,原始列表myList将仅返回1和2。