在C#中,向类添加(深层)复制功能的首选方法是什么?是应该实现复制构造函数,还是从派生ICloneable并实现该Clone()方法?
备注:我在括号内写了"深刻",因为我认为这是无关紧要的.显然其他人不同意,所以我问复制构造函数/操作符/函数是否需要明确它实现的副本变体.
是否有经验法则有助于确定在哪种情况下使用哪个?我最喜欢哪一个?
谢谢!
我尝试了以下内容来分离实体对象的图形,然后将其附加到新的上下文:
// create a context
var ctx = new TestEntities();
var parents = ctx.Parents;
// populate the graph
var newParent = new Parent {Nb = 1, Title = "Parent1"};
parents.AddObject(newParent);
newParent.Children.Add(new Child {Nb = 1, Title = "Child1"});
// put all entity objects in Unchanged state before detaching
ctx.SaveChanges();
// detach all entity objects
foreach (var objectStateEntry in ctx.ObjectStateManager.GetObjectStateEntries(~EntityState.Detached))
ctx.Detach(objectStateEntry.Entity);
// create a new context
ctx = new TestEntities();
// attach graphs to new context
foreach (var p in parents) …Run Code Online (Sandbox Code Playgroud)