我在c#中有一个对象的通用列表,并希望克隆列表。列表中的项是可克隆的,但似乎没有做list. clone()的选项。

有什么简单的办法吗?


当前回答

除非需要对List<T>中的每个对象进行实际克隆,否则克隆列表的最佳方法是使用旧列表作为集合参数创建一个新列表。

List<T> myList = ...;
List<T> cloneOfMyList = new List<T>(myList);

对myList的更改,如插入或删除,将不会影响cloneOfMyList,反之亦然。

然而,两个list所包含的实际对象仍然是相同的。

其他回答

public class CloneableList<T> : List<T>, ICloneable where T : ICloneable
{
  public object Clone()
  {
    var clone = new List<T>();
    ForEach(item => clone.Add((T)item.Clone()));
    return clone;
  }
}

如果你需要一个具有相同容量的克隆列表,你可以尝试这样做:

public static List<T> Clone<T>(this List<T> oldList)
{
    var newList = new List<T>(oldList.Capacity);
    newList.AddRange(oldList);
    return newList;
}

如果你只关心值类型……

你知道这种类型:

List<int> newList = new List<int>(oldList);

如果你之前不知道类型,你需要一个helper函数:

List<T> Clone<T>(IEnumerable<T> oldList)
{
    return newList = new List<T>(oldList);
}

公正:

List<string> myNewList = Clone(myOldList);

您还可以使用ToArray简单地将列表转换为数组,然后使用array . clone(…)克隆数组。 根据您的需要,Array类中包含的方法可以满足您的需要。

public static Object CloneType(Object objtype)
{
    Object lstfinal = new Object();

    using (MemoryStream memStream = new MemoryStream())
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
        binaryFormatter.Serialize(memStream, objtype); memStream.Seek(0, SeekOrigin.Begin);
        lstfinal = binaryFormatter.Deserialize(memStream);
    }

    return lstfinal;
}