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