MemberwishClone学习

时间:2022-03-20 18:56:27
/*
* Created by SharpDevelop.
* User: My little flower basket
* Date: 2013/7/12
* Time: 9:37
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System; namespace Task2
{
class MyCopyableClass
{
protected int myInt; public int ContainedInt
{
get
{
return myInt;
}
set
{
myInt = value;
}
} public MyCopyableClass GetCopy()
{
return (MyCopyableClass)MemberwiseClone();//如果这个类中有引用将会被改变,这是一个浅表复制 。所谓深度复制 ,就是当遇到引用时不是复制一个指针而是建立一个全新的对象
}
} class Program
{
public static void Main(string[] args)
{
MyCopyableClass obj1 = new MyCopyableClass();
obj1.ContainedInt = 5; MyCopyableClass obj2 = obj1.GetCopy();
obj1.ContainedInt = 9; Console.WriteLine(obj2.ContainedInt); Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
//
}
}
}