如何在没有任何参考创建类对象的副本? [英] How to create copy of class object without any reference?

查看:197
本文介绍了如何在没有任何参考创建类对象的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个类的对象没有任何参考的副本? ICloneable 使得类对象的拷贝(通过浅拷贝),但不支持深度复制。我找了一个功能,足够聪明,读一类对象的所有成员,并作出深刻复制到另一个对象,而无需指定成员名称。


解决方案

我已经看到了这个作为一个解决方案,基本上是写自己的函数来做到这一点,因为你说过ICloneable没有做深副本



<$ p $什么p> 使用(MemoryStream的毫秒=新的MemoryStream())
{
的BinaryFormatter格式=新的BinaryFormatter(公共静态牛逼正是deepcopy(T除外)
{
);
formatter.Serialize(MS,等);
ms.Position = 0;
回报率(T)formatter.Deserialize(MS);
}
}



我引用这个线程。 复制一个类,C#


How do I create a copy of a class object without any reference? ICloneable makes a copy of a class object (via shallow copy) but doesn't support deep copying. I am looking for a function that is smart enough to read all members of a class object and make a deep copy to another object without specifying member names.

解决方案

I've seen this as a solution, basically write your own function to do this since what you said about ICloneable not doing a deep copy

public static T DeepCopy(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

I'm referencing this thread. copy a class, C#

这篇关于如何在没有任何参考创建类对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆