开发者

Pass List to method without modifying original list

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&开发者_Python百科lt;int>();
    public CopyTest1(List<int> l)
    {
        foreach (int num in l)
        {
            _myList.Add(num);
        }
        _myList.RemoveAt(0); // no effect on original List
    }
}


duplicate the list:

_myLocalList = new List<int>(_myList);

and perform the operations on the local list.


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()) .


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜