gpt4 book ai didi

c# - 在 C# 中克隆对象

转载 作者:太空狗 更新时间:2023-10-30 00:46:41 24 4
gpt4 key购买 nike

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

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# - 在 C# 中克隆对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2585652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com