Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

c# - Cloning objects without Serialization

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...