Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...