http://xiangai.taobao.com
http://shop148612228.taobao.com

Clone()方法C#

class DrawBase:System.Object , ICloneable

{

public string name = "jmj";

public DrawBase()

{

}

public object Clone()

{

return this as object; //引用同一个对象

return this.MemberwiseClone(); //浅复制

return new DrawBase() as object;//深复制

}

}

class Program

{

static void Main(string[] args)

{

DrawBase rect = new DrawBase();

Console.WriteLine(rect.name);

DrawBase line = rect.Clone() as DrawBase;

line.name = "a9fs3";

Console.WriteLine(rect.name);

DrawBase ploy = line.Clone() as DrawBase;

ploy.name = "lj";

Console.WriteLine(rect.name);

Console.WriteLine(object.ReferenceEquals(line, ploy));

Console.ReadLine();

}

}

运行结果:

return this as object; //引用同一个对象

输出:jmj

a9fs3

lj

True

return this.MemberwiseClone(); //浅复制

return new DrawBase() as object;//深复制

输出均为: jmj

jmj

jmj

False

解释:

return this as object 方法总是引用同一个对象,因此相应的堆内存上的值会改变!

后两种方法都是对对象的复制,区别在于复制的类别不同:深复制会复制整个填充的对象,包括该对象中其他引用类型值类型的值;而浅复制只复制了一个对象中所有引用,它没有值的复制,通过引用它们的其他对象的引用来共享它们。

posted @ 2013-09-27 21:07  万事俱备就差个程序员  阅读(3798)  评论(0编辑  收藏  举报

http://xiangai.taobao.com
http://shop148612228.taobao.com
如果您觉得对您有帮助.领个红包吧.谢谢.
支付宝红包
微信打赏 支付宝打赏