欢迎使用CSDN-markdown编辑器
2015-10-20 11:06
295 查看
namespace Light_Sharp { public class Printor { int printID; public int PrintID { get; set; } public Printor(int newID) { PrintID = newID;a } public object GetCopy() { return MemberwiseClone(); } } public class program { public static void Main(string[] args) { Printor print1 = new Printor(13000); Printor copytprint = (Printor)print1.GetCopy(); print1.PrintID = 12000; Console.WriteLine("print1 ID:{0}",print1.PrintID); Console.WriteLine("copyprint ID:{0}",copytprint.PrintID); Console.ReadKey(); } } }
运行程序会得到输出:
print1 ID:12000
copyprint ID:13000
浅复制适用于用于类成员变量没有引用的情况下,如果有引用变量,就要用深复制了。
下面的代码反应了如果成员变量有引用会发生的状况,当我们修改对象print1中carbon的硬度hard时,copyprint中carbon的硬度hard也变成了9,那是因为两个对象中的carbon引用实际上指向
了同一个对象。
输出结果:
print1’s carbon hard:9
copyprint’s carbon hard:9
namespace Light_Sharp { public class Carbon { int hard; public int Hard { get; set; } public Carbon(int hard) { Hard = hard; } } public class Printor { public Carbon carbon = new Carbon(10); int printID; public int PrintID { get; set; } public Printor(int newID) { PrintID = newID; } public object GetCopy() { return MemberwiseClone(); } } public class program { public static void Main(string[] args) { Printor print1 = new Printor(13000); Printor copytprint = (Printor)print1.GetCopy(); print1.carbon.Hard = 9; Console.WriteLine("print1's carbon hard:{0}",print1.carbon.Hard); Console.WriteLine("copyprint's carbon hard:{0}", copytprint.carbon.Hard); Console.ReadKey(); } } }
为了实现深复制,那么该怎么办呢?
其实微软的.NetFramework提供了标准的实现方式——继承ICloneable接口,
该接口有一个Clone()方法,该方法不带任何参数,并且返回一个object类型的对象。
签名跟上面的GetCopy()方法相同。修改Printor类,已实现深复制代码如下:
这里写代码片public class Carbon { int hard; public int Hard { get; set; } public Carbon(int hard) { Hard = hard; } } public class Printor : ICloneable { public Carbon carbon = new Carbon(10); int printID; public int PrintID { get; set; } public Printor(int newID) { PrintID = newID; } public object Clone() { Printor printorClone = new Printor(PrintID); printorClone.carbon.Hard = carbon.Hard; return printorClone; } } public class program { public static void Main(string[] args) { Printor print1 = new Printor(13000); Printor copytprint = (Printor)print1.Clone(); print1.carbon.Hard = 9; Console.WriteLine("print1's carbon hard:{0}",print1.carbon.Hard); Console.WriteLine("copyprint's carbon hard:{0}", copytprint.carbon.Hard); Console.ReadKey(); } }
输出结果:
print1’s carbon hard:9
copyprint’s carbon hard:10
相关文章推荐
- jquery设置控件不能复制粘贴
- IE11浏览器:请不要再叫我IE,谢谢
- DMA传输数据过程简介
- 深入理解Android的startservice和bindservice
- jquery form插件(ajax)上传文件实现及原理
- lua 字符匹配
- 【面试题】连续子数组的最大和
- [置顶] [实验-视频过程]常用的oracle数据字典
- 【译】Playgrounds中的字面量(Literals)
- ocp-530
- android之事件分发传递机制
- c++自定义消息管理机制升级版(std::bind && std::function)
- 小逻辑
- httplistener 在写入所有字节之前不能关闭流
- ajax提交后取得的List处理
- 远程桌面连接数超过限制解决方法
- ocp-529
- mov edi,edi - hook api
- 张国祥老师在宁波恒周贸易公司主讲管理体系建设实务方法
- ocp-528