将List传递给方法而不修改原始列表

本文关键字:修改 原始 列表 方法 List | 更新日期: 2023-09-27 18:10:55

这是将List传递给方法并编辑List而不修改原始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
    }
}

将List传递给方法而不修改原始列表

复制列表:

_myLocalList = new List<int>(_myList);

,对本地列表执行操作。

使用AsReadOnly:

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

并通过CopyTest1(yourList.AsReadOnly())调用。

还有另一种方法。您可以使用List<T>的复制构造函数:

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

将列表中的对象克隆到其他列表中,并在此副本上工作

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

当你将一个列表传递给一个方法时,你传递了一个指向该列表的指针,这就是为什么当你在你的方法中修改它时你改变了'原始'列表。如果你想修改列表的副本,你只需要创建一个。在调用CopyTest1的代码中,您可以基于原始列表创建一个新列表:

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

可以通过引用传递对象,操作如下:

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

编辑:这个问题现在已经澄清了,OP是在寻找一种不改变原始列表的方法。