Clone()方法C#

return return return

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 方法總是引用同一個對象,因此相應的堆記憶體上的值會改變!
後兩種方法都是對對象的複製,區別在於複製的類別不同:深複製會複製整個填充的對象,包括該對象中其他引用類型和值類型的值;而淺複製只複製了一個對象中所有引用,它沒有值的複製,通過引用它們的其他對象的引用來共享它們。

相關詞條

相關搜尋

熱門詞條

聯絡我們