我有一个列表,其中包含来自操作的一些数据,我将其存储在内存缓存中.现在我想要另一个列表,其中包含基于某些条件的列表中的一些子数据.
从下面的代码可以看出,我正在对目标列表进行一些操作.问题是我对目标列表所做的任何更改也都在对mainList进行.我认为它因为参考是相同的或什么的.
我需要的是目标列表上的操作不会影响主列表中的数据.
List<Item> target = mainList;
SomeOperationFunction(target);
void List<Item> SomeOperationFunction(List<Item> target)
{
target.removeat(3);
return target;
}
Run Code Online (Sandbox Code Playgroud)
Ler*_*eri 20
您需要在方法中克隆列表,因为它List<T>是一个类,所以它是引用类型并通过引用传递.
例如:
List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = target.ToList();
tmp.RemoveAt(3);
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
要么
List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = new List<Item>(target);
tmp.RemoveAt(3);
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
要么
List<Item> SomeOperationFunction(List<Item> target)
{
List<Item> tmp = new List<Item>();
tmp.AddRange(target);
tmp.RemoveAt(3);
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
您需要复制列表,以便对副本的更改不会影响原件.最简单的方法是使用ToList扩展方法System.Linq.
var newList = SomeOperationFunction(target.ToList());
Run Code Online (Sandbox Code Playgroud)
首先构建一个新列表并对其进行操作,因为 List 是一种引用类型,即当您在函数中传递它时,您不仅传递值,而且传递实际对象本身。
如果你只是赋值target给mainList,两个变量都指向同一个对象,所以你需要创建一个新的 List:
List<Item> target = new List<Item>(mainList);
Run Code Online (Sandbox Code Playgroud)
void List<Item> SomeOperationFunction()没有意义,因为要么不返回任何内容 ( void),要么返回List<T>. 因此,要么从您的方法中删除 return 语句,要么返回一个新的List<Item>. 在后一种情况下,我会将其重写为:
List<Item> target = SomeOperationFunction(mainList);
List<Item> SomeOperationFunction(List<Item> target)
{
var newList = new List<Item>(target);
newList.RemoveAt(3);
return newList;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24569 次 |
| 最近记录: |