.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 }



posted on 2011-12-26 11:47  risan  阅读(294)  评论(0编辑  收藏  举报