我们自己写代码的时候经常会直接赋值,然而对于C#而言,除了基本的数据类型,我们所构建的其他类都会要用到深拷贝才能拷贝到一个新的对象当中,若是直接引用,无异于指向同一个对象。
[Serializable] //用于深复制的类加上这个
public class ShippingModel : IComparable
{
.... //这些是每个属性
//深拷貝賦值
public ShippingModel DeepClone()
{
using (Stream objectStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, this);
objectStream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(objectStream) as ShippingModel;//返回深拷贝的类
}
}
}
引用的时候调用即可
ShippingModel model = new ShippingModel();
model = Shipping.DeepClone();//深拷贝一个对象
第二种方法,直接创建复制类
public class Clone
{
/// <summary>
/// 深克隆
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static T DepthClone<T>(T t)
{
T clone = default(T);
using (Stream stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(stream, t);
stream.Seek(0, SeekOrigin.Begin);
clone = (T)formatter.Deserialize(stream);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
}
return clone;
}
}
使用的时候
Student stu1 = new Student();//实例化一个对象
stu1.obj = new object();//实例化对象中的引用对象
Student stu2 = Clone.DepthClone(stu1);//深克隆对象