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 方法總是引用同一個對象,因此相應的堆記憶體上的值會改變!