当前位置 博文首页 > 匆匆那年:C#: 浅拷贝与深拷贝区别
代码如下:
public enum myEnum
{ _1 = 1, _2 = 2 }
//结构体
public struct myStruct
{
public int _int;
public myStruct(int i)
{ _int = i; }
}
//类
class myClass
{
public string _string;
public myClass(string s)
{ _string = s; }
}
//ICloneable:创建作为当前实例副本的新对象。
class DemoClass : ICloneable
{
public int _int = 1;
public string _string = "1";
public myEnum _enum = myEnum._1;
public myStruct _struct = new myStruct(1);
public myClass _class = new myClass("1");
//数组
public int[] arrInt = new int[] { 1 };
public string[] arrString = new string[] { "1" };
//返回此实例副本的新对象
public object Clone()
{
//MemberwiseClone:返回当前对象的浅表副本(它是Object对象的基方法)
return this.MemberwiseClone();
}
}
注意:
ICloneable 接口:支持克隆,即用与现有实例相同的值创建类的新实例。
然后,改变实例B 的值,并观察实例A 的值会不会被改变。
代码如下:
class 浅拷贝与深拷贝
{
static void Main(string[] args)
{
DemoClass A = new DemoClass();
//创建实例A的副本 --> 新对象实例B
DemoClass B = (DemoClass)A.Clone();
B._int = 2;
Console.WriteLine(" int \t\t A:{0} B:{1}", A._int, B._int);
B._string = "2";
Console.WriteLine(" string \t A:{0} B:{1}", A._string, B._string);
B._enum = myEnum._2;
Console.WriteLine(" enum \t\t A:{0} B:{1}", (int)A._enum, (int)B._enum);
B._struct._int = 2;
Console.WriteLine(" struct \t A:{0} B:{1}",
A._struct._int, B._struct._int);
B._class._string = "2";
Console.WriteLine(" class \t\t A:{0} B:{1}",
A._class._string, B._class._string);
B.arrInt[0] = 2;
Console.WriteLine(" intArray \t A:{0} B:{1}",
A.arrInt[0], B.arrInt[0]);
B.arrString[0] = "2";
Console.WriteLine(" stringArray \t A:{0} B:{1}",
A.arrString[0], B.arrString[0]);
Console.ReadKey();
}
}
结果如下:
从最后的输出结果,我们得知:
对于内部的Class 对象和数组,则Copy 一份地址。[改变B 时,A也被改变了]
而对于其它内置的int / string / enum / struct / object 类型,则Copy 一份值。
有一位网友说:
string 类型虽然是引用类型,但是很多情况下.Net 把string 做值类型来处理,我觉得string 应该也是按照值类型处理的。
这说明他对string 类型还不够了解。
可以肯定的是:string 一定是引用类型。那它为什么是深拷贝呢?
如果你看一下string 类型的源代码就知道了:
//表示空字符串。此字段为只读。
public static readonly string Empty;
答案就在于 string 是 readonly 的,当改变 string 类型的数据值时,将重新分配了内存地址。
下面引用一段网友的代码:Vseen[Aloner] 的个人陋见:
public class Student
{
// 这里用“字段”,其实应当是属性。
public string Name;
public int Age;
//自定义类 Classroom
public Classroom Class;
}
浅拷贝:Student A 浅拷贝出 Student B,Name和Age拥有新的内存地址,但引用了同一个 Classroom。
public object Clone()
{
Student B = new Student();
B.Name = this.Name;
B.Age = this.Age;
//浅拷贝
B.Class = this.Class;
//深拷贝
B.Class = new Classromm();
B.Class.Name = this.Class.Name;
B.Class.Teacher = this.Class.Teacher;
//根据情况,对Teacher 进行判定要进行的是深拷贝,还是浅拷贝。
}
浅拷贝:给对象拷贝一份新的对象。