通过序列化和反序列化实现深拷贝

.NET中使用ObjectMemberwiseClone()方法来实现浅拷贝,通过序列化和反序列化实现深拷贝,后者代价比较大

 1 class FootMan : Enemy
2 {
3 private string model;
4
5 public FootMan(int power, int speed, Location location)
6 : base(power, speed, location)
7 {
8 model = "footman";
9 }
10
11 public override void ShowInfo()
12 {
13 Console.WriteLine("model:{0} power:{1} speed:{2} location:({3},{4})", model, power, speed, location.x, location.y);
14 }
15
16 public override Enemy Clone(bool isDeepCopy)
17 {
18 FootMan footman;
19 if (isDeepCopy)
20 {
21 MemoryStream memoryStream = new MemoryStream();
22 BinaryFormatter formatter = new BinaryFormatter();
23 formatter.Serialize(memoryStream, this);
24 memoryStream.Position = 0;
25 footman = (FootMan)formatter.Deserialize(memoryStream);
26 }
27 else
28 footman = (FootMan)this.MemberwiseClone();
29 return footman;
30 }
31
32 public void FootmanAttack()
33 {
34 Console.WriteLine("FootmanAttack");
35 }
36 }



转载于:https://www.cnblogs.com/lican/archive/2011/12/26/2301823.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值