通过序列化来实现对象深度复制。

1  public static T Clone<T>(T obj)
2  {
3    object result;
4    using (var memoryStream = new MemoryStream())
5    {
6      var binaryFormatter = new BinaryFormatter();
7      binaryFormatter.Serialize(memoryStream, obj);
8      memoryStream.Seek(0, SeekOrigin.Begin);
9      result = binaryFormatter.Deserialize(memoryStream);
10    }
11    return (T)result;
12  }

[Serializable]

public class Item

{

  public int Id {get;set;}

  public string Name{get;set;}

}

Item obj1 = new Item{Id = 1, Name = "Test"};

Item obj2 = Clone<Item>(obj1);

obj1 will not equal obj2

posted on 2011-03-16 15:02  rroo  阅读(218)  评论(0编辑  收藏  举报