通过序列化来实现对象深度复制。
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 }
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