编程语言
首页 > 编程语言> > 在C#中克隆对象

在C#中克隆对象

作者:互联网

我用虚拟属性定义了下一个类:

public class Order: BaseEPharmObject
{
    public Order()
    {
    }

    public virtual Guid Id { get; set; }
    public virtual DateTime Created { get; set; }
    public virtual DateTime? Closed { get; set; }
    public virtual OrderResult OrderResult { get; set; }
    public virtual decimal Balance { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual Shift Shift { get; set; }
    public virtual Order LinkedOrder { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual decimal TotalPayable { get; set; }

    public virtual IList<Transaction> Transactions { get; set; }
    public virtual IList<Payment> Payments { get; set; }
}

并尝试克隆该派生类的对象.如何在基类中实现深层复制?

解决方法:

如果你的类型是serializable,你可以使用BinaryFormatter

public static T DeepClone<T>(T obj)
{
    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, obj);
        stream.Position = 0;
        return (T)formatter.Deserialize(stream);
    }
}

标签:c,deep-copy,cloning
来源: https://codeday.me/bug/20190526/1159164.html