代码
1 /// <summary>
2 /// 深拷贝对象副本
3 /// </summary>
4 /// <typeparam name="T"></typeparam>
5 /// <param name="obj"></param>
6 /// <returns></returns>
7 public static T DeepClone<T>(this T obj) {
8 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
9 System.IO.MemoryStream ms = new System.IO.MemoryStream();
10 T copy=default(T);
11 try {
12 formatter.Serialize(ms, obj);
13 ms.Seek(0, System.IO.SeekOrigin.Begin);
14 copy = (T)formatter.Deserialize(ms);
15 } catch (Exception ex) {
16 throw new Exception("深拷贝对象实例出错。", ex);
17 } finally {
18 ms.Close();
19 }
20 return copy;
21 }
22