不幸的是,您在这里所做的是将变量设置draftProjectEntity
为对projectEntity
对象的引用。也就是说,它们现在指向同一个对象。您需要做的是对projectEntity
.
有很多方法可以使用反射来做到这一点——如果你要经常这样做——那么我强烈建议你研究这种方法。
但是,如果您只深入一个级别,或者只针对一小部分对象图,那么可能值得简单地手动完成并在您的实体上实现您自己的 IDeepCloneable ......
public interface IDeepCloneable<T>
{
T DeepClone();
}
public class Person : IDeepCloneable<Person>
{
public string Name { get; set; }
public IList<Address> Addresses { get; set; }
public Person DeepClone()
{
var clone = new Person() { Name = Name.Clone().ToString() };
//have to make a clone of each child
var addresses = new List<Address>();
foreach (var address in this.Addresses)
addresses.Add(address.DeepClone());
clone.Addresses = addresses;
return clone;
}
}
public class Address : IDeepCloneable<Address>
{
public int StreetNumber { get; set; }
public string Street { get; set; }
public string Suburb { get; set; }
public Address DeepClone()
{
var clone = new Address()
{
Street = this.Street.Clone().ToString(),
StreetNumber = this.StreetNumber, //value type - no reference held
Suburb = this.Suburb.Clone().ToString()
};
return clone;
}
}
//usage:
var source = personRepository.FetchByName("JoeBlogs1999");
var target = source.DeepClone();
//at this point you could set any statuses, or non cloning related changes to the copy etc..
targetRepository.Add(target);
targetRepository.Update;
有关为什么我不为此使用 ICloneable 接口的信息...请查看此线程:在实现 ICloneable 时我应该提供深度克隆吗?