How do I clone a generic list in C#?

前端 未结 26 2821
失恋的感觉
失恋的感觉 2020-11-22 01:27

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()

26条回答
  •  一个人的身影
    2020-11-22 02:08

    My friend Gregor Martinovic and I came up with this easy solution using a JavaScript Serializer. There is no need to flag classes as Serializable and in our tests using the Newtonsoft JsonSerializer even faster than using BinaryFormatter. With extension methods usable on every object.

    Standard .NET JavascriptSerializer option:

    public static T DeepCopy(this T value)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
    
        string json = js.Serialize(value);
    
        return js.Deserialize(json);
    }
    

    Faster option using Newtonsoft JSON:

    public static T DeepCopy(this T value)
    {
        string json = JsonConvert.SerializeObject(value);
    
        return JsonConvert.DeserializeObject(json);
    }
    

提交回复
热议问题