.Net Deep cloning - what is the best way to do that?

前端 未结 7 2189
小蘑菇
小蘑菇 2020-12-05 20:39

I need to perform deep cloning on my complex object model. What do you think is the best way to do that in .Net?
I thought about serializing / Deserializing
no need

7条回答
  •  广开言路
    2020-12-05 21:05

    If you are running code in a Partial Trust environment such as the Rackspace Cloud you will likely be restricted from using the BinaryFormatter. The XmlSerializer can be used instead.

    public static T DeepClone(T obj)
    {
        using (var ms = new MemoryStream())
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            xs.Serialize(ms, obj);
            ms.Position = 0;
    
            return (T)xs.Deserialize(ms);
        }
    }
    

提交回复
热议问题