在 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; }
}
并尝试克隆该派生类的对象。如何在基类中实现深拷贝?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的类型是可序列化,您可以使用BinaryFormatter:
If your types are serializable you could use BinaryFormatter:
最好的方法通常是序列化实例并将其重新水合为新实例。 此处描述了执行此操作的一种方法。
我对本文的唯一警告是,不要将其实现为 ICloneable - 该接口已被弃用,并且会让类的调用者感到困惑。最好的办法是将此实现移至实用方法中并在那里调用它。
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.