C#中深度复制和浅度复制详解
本文章主要是讲解C#语言编程中,深度复制和浅度复制,下面我将通过一个实例进行讲解。在实例开发之前,我们得先知道深度复制是什么和浅度复制是什么,它们之间的区别又是什么,下面将为大家一一揭晓。
1.深度复制是什么?
深度复制就是引用类型的复制。
2.浅度复制是什么?
浅度复制是值类型的复制。
以下是C#中深度复制和浅度复制的实例代码引用片段:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
namespaceTest
{
publicclassContent
{
publicintval;
}
//此处若是深度复制才继承ICloneable接口
//publicclassCloner:ICloneable
publicclassCloner
{
publicContentMyContent=newContent();
publicCloner(intnewVal)
{
MyContent.val=newVal;
}
//浅度复制
//使用System.Object.MemberwiseClone()进行浅度复制,使用getCopy方法.
publicobjectgetCopy()
{
returnMemberwiseClone();
}
//深度复制:
publicobjectclone()
{
ClonerclonedCloner=newCloner(MyContent.val);//此处是实例化一个对象
returnclonedCloner;
}
}
}
//主函数
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
namespaceTest
{
classProgram
{
staticvoidMain(string[]args)
{
ClonermySource=newCloner(5);
ClonermyTarget=(Cloner)mySource.getCopy();//深度为cloner
Console.WriteLine("MyTarget.Mycontent.Val={}",myTarget.MyContent.val);
mySource.MyContent.val=2;
Console.WriteLine("MyTarget.Mycontent.Val={}",myTarget.MyContent.val);
}
}
}
通过简单的实例开发,大家对深度复制和浅度复制是不是有了大概的了解了,以后再有相关的内容介绍会在和大家分享哦