将列表传递到方法中,在不影响“原始"效果的情况下修改方法中的列表 [英] Passing a List into a method, modify the list within the method without affecting 'original'

查看:31
本文介绍了将列表传递到方法中,在不影响“原始"效果的情况下修改方法中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果该主题含糊不清,我会尽可能地总结一下,而又不知道我要实现的目标的确切术语.

Sorry if the subject seems vague, I tried summing it up as best I can without knowing the exact terminology of what I'm trying to achieve.

基本上我有一个列表,然后调用一个方法

Essentially I have a list and then I call a method

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

在我的方法中,我想这样做(例如)

In my method I'd like to do this (for example)

public void doSomething (List<int> myPassedList) 
{

    int A = 5;
    myPassList.Add (A);
    //... And then some other cool code with this modified list
}

但是,我不想更改原始列表,我希望它保持原样.本质上,当我将列表传递给方法时,我想要一个列表的副本,然后在每次调用该方法时将其复制.

However, I dont want the original list changed, I want it exactly as it was. Essentially when I pass the list into the method I'd like a duplicate of the list, which is then made new each time the method is called.

我想看到控制台先打印"1",然后打印"2"

I want to see the console print '1' then '2'

但是它将打印'1','2'和'5'

but it will print '1', '2' and '5'

希望这一切都有道理!非常感谢您的帮助

Hopefully this all makes sense! Thanks very much in advance for any help

吉姆

推荐答案

List 是引用类型,因此当您将 myPassedList 作为参数传递给 doSomething 您正在修改原始列表.

List is a reference type so when you pass myPassedList as an argument to doSomething you are modifying the original list.

您有两个选择,可以调用 ToList() 或创建一个新列表,例如:

You have two options, either call ToList() or create a new list, as an example:

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
}

原始列表 myList 将仅返回1和2.

The original list myList will then only return 1 and 2.

这篇关于将列表传递到方法中,在不影响“原始"效果的情况下修改方法中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆