我有一个希望用户编辑的自定义对象,但是在编辑之前,我想对该对象进行备份,以便在必要时进行还原。
基本上,用户将拥有具有所需所有信息的ObjectA,然后单击“编辑”,将ObjectA的备份创建为ObjectB,用户可以对ObjectA进行更改,然后用户可以单击“取消”以放弃所有更改制成ObjectA,实际上只是用备份对象ObjectB替换了ObjectA。
制作新对象而不是简单地创建对该对象的另一个引用的最佳方法是什么?
// User has their main object
CustomObject obj = new CustomObject();
// User clicks Edit and a copy of the object is stored in case obj needs to be restored
CustomObject backupObj = obj; // This only creates a reference but I'm not sure how else to show this
// User makes changes to obj but decides to discard those changes and clicks Cancel
obj = backupObj; // obj is restored
// User goes on with the program
答案 0 :(得分:1)
标准方法是实现ICloneable
:
class CustomObject : ICloneable
{
... your implementation
public object Clone()
{
return this.MemberwiseClone();
}
}
CustomObject obj = new CustomObject();
CustomObject backupObj = (CustomerObject) obj.Clone(); //backup
...
// later restore
obj = backupObj
MemberwiseClone()
进行浅表复制。