浅拷贝只需要直接赋值,
深拷贝需要写一个函数,通过序列化与反序列化将旧的list<>对象拷贝到新的List<>对象,具体代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LstCopy
{
public partial class Form1 : Form
{
[Serializable]
public class USER
{
public string name;
public int id;
}
public Form1()
{
InitializeComponent();
List<USER> users = new List<USER>();
for(int i=0;i< 10;i++)
{
USER user = new USER();
user.name = "name" + i.ToString();
user.id = i;
users.Add(user);
}
List<USER> tempLst = Clone<USER>(users);//深拷贝
//List<USER> tempLst = users;//浅拷贝
tempLst = tempLst.FindAll(p=>p.id>5).ToList();
tempLst[0].name = "changed";
}
public static List<T> Clone<T>(object List)
{
using (Stream objectStream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, List);
objectStream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(objectStream) as List<T>;
}
}
}
}