Pass List to method without modifying original list

ε祈祈猫儿з 提交于 2019-12-05 00:12:59

问题


Is this the only way of passing a List to a method and editing that List, without modifying the original List?

class CopyTest1
{
    List<int> _myList = new List<int>();
    public CopyTest1(List<int> l)
    {
        foreach (int num in l)
        {
            _myList.Add(num);
        }
        _myList.RemoveAt(0); // no effect on original List
    }
}

回答1:


duplicate the list:

_myLocalList = new List<int>(_myList);

and perform the operations on the local list.




回答2:


Use AsReadOnly for this:

class CopyTest1
{
    List<int> _myList = new List<int>();
    public CopyTest1(IList<int> l)
    {
        foreach (int num in l)
        {
            _myList.Add(num);
        }
        _myList.RemoveAt(0); // no effect on original List
    }
}

And call it via CopyTest1(yourList.AsReadOnly()) .




回答3:


There is another way. You can use the copy constructor of List<T>:

List<int> _myList;
public CopyTest1(List<int> l)
{
    _myList = new List<int>(l);
}



回答4:


Clone objects in the list to other list and work on this copy

static class Extensions
{
        public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
        {
                return listToClone.Select(item => (T)item.Clone()).ToList();
        }
}



回答5:


When you pass a list to a method you pass a pointer to said list, that's why your changing the 'original' list when you modify it inside your method. If you instead want to modify a copy of the list you just need to make one. In the code that calls CopyTest1 you can create a new list based on your original list:

public void CallsCopyTest1()
{
    var originalList = new List<int>();
    var newList = new List<int>(originalList);
    var copyTest = new CopyTest1(newList); //Modifies newList not originalList
}
class CopyTest1
{
    List<int> _myList = new List<int>();
    public CopyTest1(List<int> l)
    {
        foreach (int num in l)
        {
            _myList.Add(num);
        }
        _myList.RemoveAt(0); // no effect on original List
    }
}



回答6:


You can pass an object by reference doing the following:

public static void ReferenceMethod(ref List<T> myParam) {
    ...
} 

EDIT: The question has now been clarified, the OP was after a way not to alter the original list.



来源:https://stackoverflow.com/questions/7712842/pass-list-to-method-without-modifying-original-list

工具导航Map

JSON相关