Pal*_*lus 5 c# list pass-by-reference
这是将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
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*eas 12
复制列表:
_myLocalList = new List<int>(_myList);
Run Code Online (Sandbox Code Playgroud)
并在本地列表上执行操作.
使用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
}
}
Run Code Online (Sandbox Code Playgroud)
并通过CopyTest1(yourList.AsReadOnly()).