从您提供的小代码中,我假设两者都MainPic
将OriginalPic
引用同一个对象-> 对一个引用的更改也会影响另一个引用。您实际上需要创建一个包含原始信息的备份图片,您需要创建一个deep copy
您的图片。
参考这篇文章:
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}
这将创建您的深层副本,Image
您可以使用它来将图像恢复到其原始状态。
ICloneable
此外,我还找到了使用-Interface的教程:
要获得对象的深层副本,您必须为 Invoice 及其所有相关类实现 IClonable 接口:
public class Invoice: IClonable
{
public int No;
public DateTime Date;
public Person Customer;
//.............
public object Clone()
{
Invoice myInvoice = (Invoice)this.MemberwiseClone();
myInvoice.Customer = (Person) this.Customer.Clone();
return myInvoice;
}
}
public class Person: IClonable
{
public string Name;
public int Age;
public object Clone()
{
return this.MemberwiseClone();
}
}
编辑
似乎System.Windows.Controls.Image
无法序列化......您可以尝试从中派生并实现ISerializable
或创建(static
)方法并手动创建克隆。然而,这些步骤中的任何一个都是必要的!