无需序列化即可克隆对象 [英] Cloning objects without Serialization

查看:33
本文介绍了无需序列化即可克隆对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SO上找到了许多解决方案,否则它们通过序列化/反序列化(进入内存和返回)来处理对象的深克隆。

I've found numerous solutions here at SO and elsewere that deal with deep clone of object via serialization/deserialization (into memory and back).

要克隆的类标记为 [Serializable] 。我碰巧将我的类(其中大多数是用 [DataContract] 标记)的,因为我使用了 DataContractSerializer 进行序列化XML。

It requires that classes to be cloned are marked with [Serializable]. I happen to have my classes (well most of them) marked with [DataContract] because I use DataContractSerializer to serialize into XML.

我只介绍了 [Serializable] 属性,因为需要深度克隆其中一些类实例。但是,现在通过DCS进行序列化/反序列化时发生了一些事情,因为它不再起作用了-有关在反序列化中期望使用其他XML元素的错误。如果删除 [可序列化] ,错误就消失了。

I only introduced [Serializable] attribute because of the need for deep clone of some of these class instances. However, now something happened to serialization/deserialization via the DCS because it does not work anymore - errors about expecting a different XML element on deserialization. If I remove the [Serializable] the errors are gone.

我有什么选择?我只是想尽可能地简单地克隆对象。

What are my options? I just want to deep clone my objects as simple as possible.

推荐答案

这可行

    public static T DeepClone<T>(this T a)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            DataContractSerializer dcs = new DataContractSerializer(typeof(T));
            dcs.WriteObject(stream, a);
            stream.Position = 0;
            return (T)dcs.ReadObject(stream);
        }
    }

这篇关于无需序列化即可克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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