首先我们需要了解一下引用类型和值类型
1、byte,short,int,long,float,double,decimal,char,bool 和 struct 统称为值类型。值类型在声明变量后便分配了内存,值类型存储在堆栈中。
2、list,class,interface,delegete,object,string[],array 等为引用类型,引用类型变量的赋值只复制对对象的引用,而不复制对象本身,当复制的值改变时,本身的对象也会随之改变。引用类型存储在托管堆上。
实现引用类型深度克隆示例
声明类并继承ICloneable
public class ResultList : ICloneable
{
public int id { get; set; }
public string name { get; set; }
public object Clone()
{
ResultList result = new ResultList ();
result.id = this.id;
result.name= this.name;
return result;
}
}
使用类进行深度克隆
static void Main(string[] args)
{
var result = new List<ResultList>();
var info = new ResultList();
info.id = 1;
info.name = "john";
result.Add(info);
var resultclone = new List<ResultList>(); //声明新的List用来装克隆的数据
result.ForEach(t => { resultclone.Add(t.Clone() as ResultList); }); //深度克隆
resultclone.FirstOrDefault().name = "john1"; //深度克隆后修改名称并不会影响原来list的值
Console.log("result:" + result.FirstOrDefault().name);
Console.log("resultclone:" + resultclone.FirstOrDefault().name);
//输出结果为
//result:john
//resultclone:john1
}