我有两个对象,我们称它们为A,B和method
List<B> DoSomething(ref A a, List<B> b)
{
List<B> newList = new List<B>();
//
//Doing something to ref A
//
foreach(var elementOfB in b.where(...))
{
//
elementOfB.Name = "...";
//
newList.Add(elementOfB);
}
return newList;
}所以,在这个方法完成之后,我原来的list b已经改变了Name字段(string)的值,但是我没有把它作为ref传递,我使用的是应该返回elemens副本的where,对吧?所以我的问题是为什么我的list b改变了它的值?
List<B> originalList = ...;
List<B> newList = DoSomething(ref a, originalList);
//now originalList have changed Name field values发布于 2015-09-30 17:47:33
你实际上是在做浅层复制:你复制对对象的引用,而不是创建对象的克隆:
// Shallow copy (your actual implementation):
// NewList is not b, but it contains references to objects in b
var NewList = b
.Where(item => ...)
.ToList();
// Deep copy (which probably you're looking for)
// NewList doesn't contain any reference to any objects in b
var NewList = b
.Where(item => ...)
.Select(item => item.Clone()) // You need this, proving that Clone() makes a deep copy
.ToList(); 如果你想克隆这些项目,你必须为B类正确地实现ICloneable接口(以确保深度复制)
https://stackoverflow.com/questions/32862743
复制相似问题