ASP.NET----深浅拷贝问题

浅拷贝是指将对象内的数据完全一致的复制,深拷贝不是这样,它可以将内部的数据按照需要用特殊的方法拷贝,比如说对象内部有一个动态数组,浅拷贝只拷贝指针,而深拷贝可以重新申请空间并将数据复制过来。
看代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace NET.NST.Third.DeepCopy
{
public class Program
{
static void Main(string[] args)
{
DeepCopy dc
= new DeepCopy();
dc._i
= 10;
dc._a
= new A();
DeepCopy deepclone
= (DeepCopy)dc.Clone();
DeepCopy shadowclone
= (DeepCopy)dc.MemberwiseClone();

//深拷贝的拷贝对象将拥有自己的引用类型成员对象,
//所以这里的赋值不会影响原始对象
deepclone._a._s = "我是深拷贝的A";
Console.WriteLine(dc);
Console.WriteLine(deepclone);
Console.WriteLine(
"\r\n");

//浅拷贝的拷贝对象共享原始对象的引用类型成员对象,
//这里的赋值将影响原始对象
shadowclone._a._s = "我是浅拷贝的A";
Console.WriteLine(dc);
Console.WriteLine(shadowclone);
Console.Read();
}
}

public class DeepCopy : ICloneable
{
public int _i = 0;
public A _a = new A();

public object Clone()
{
//实现深拷贝
DeepCopy newdc = new DeepCopy();
newdc._a
= new A();
newdc._a._s
= _a._s;
newdc._i
= _i;
return newdc;
}

//实现浅拷贝
public new object MemberwiseClone()
{
return base.MemberwiseClone();
}
public override string ToString()
{
return "I的值为:" + _i.ToString() + ",A 为:" + _a._s;
}
}
public class A
{
public String _s = "我是原始A";
}
}

posted @ 2011-06-05 15:31  brainmao  阅读(544)  评论(0编辑  收藏  举报