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 方法总是引用同一个对象,因此相应的堆内存上的值会改变!

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM