直接List<t> list1=list2. 是地址引用。改变list1的内容,就会改变list2的内容。达不到复制、备用的要求。
下面采用对象序列化方法实现List对象复制:
1. 复制方法:
/// <summary>
/// List 对象复制,需要序列化支持
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="List"></param>
/// <returns></returns>
public static List<T> List_Clone<T>(object List)
{
using (Stream objectStream=new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(objectStream, List);
objectStream.Seek(0, SeekOrigin.Begin);
return formatter.Deserialize(objectStream) as List<T>;
}
}
调用示例:
List<EditVariableEntity> lstEve = CommonFunction.List_Clone<EditVariableEntity>(lstVar);
其它 EditVariableEntity 定义如下:
[Serializable]
public class EditVariableEntity
{
public string GroupID { get; set; }
public string ServerID { get; set; }
}
需要引用的程序集:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;