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

有什么简单的办法吗?


当前回答

如果你只关心值类型……

你知道这种类型:

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

其他回答

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

在c#中有一种使用JSON序列化器和反序列化器克隆对象的简单方法。

你可以创建一个扩展类:

using Newtonsoft.Json;

static class typeExtensions
{
    [Extension()]
    public static T jsonCloneObject<T>(T source)
    {
    string json = JsonConvert.SerializeObject(source);
    return JsonConvert.DeserializeObject<T>(json);
    }
}

克隆并反对:

obj clonedObj = originalObj.jsonCloneObject;

如果你已经参考了Newtonsoft。Json在你的项目和你的对象是可序列化的,你可以总是使用:

List<T> newList = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(listToCopy))

这可能不是最有效的方法,但除非你做了100次或1000次,否则你甚至不会注意到速度的差异。

如果你只关心值类型……

你知道这种类型:

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