How do I clone a generic list in C#?

前端 未结 26 2874
失恋的感觉
失恋的感觉 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 01:57

    After a slight modification you can also clone:

    public static T DeepClone(T obj)
    {
        T objResult;
        using (MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, obj);
            ms.Position = 0;
            objResult = (T)bf.Deserialize(ms);
        }
        return objResult;
    }
    

提交回复
热议问题