复制一个List<T>对象
对于值类型的List直接用以下方法就可以复制:
List<T> oldList = new List<T>(); oldList.Add(..); List<T> newList = new List<T>(oldList);
对于引用类型的List无法用以上方法进行复制,只会复制List中对象的引用,可以用以下扩展方法复制:
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
当然前题是List中的对象要实现ICloneable接口
另一个更保险的方法是:
public static T Clone<T>(T RealObject)
{
using (Stream objectStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, RealObject);
objectStream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(objectStream);
}
}
浙公网安备 33010602011771号