Cloning objects in C#

依然范特西╮ 提交于 2020-01-02 06:12:11

问题


I defined next class with virtual properties:

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; }
}

and trying to clone objects of that derived class. How to implement a deep copy right in the base class?


回答1:


If your types are serializable you could use 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);
    }
}



回答2:


The best way is generally to serialize the instance and rehydrate it back as a new instance. One way of doing this is described here.

My only caveat to the article is that don't implement this as ICloneable - this interface is deprecated and is confusing to callers of your class. The best thing would be to move this implementation into a utility method and call it there.



来源:https://stackoverflow.com/questions/2585652/cloning-objects-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!