Clone.cs 734 B

1234567891011121314151617181920212223242526272829
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization;
  4. using System.Runtime.Serialization.Formatters.Binary;
  5. public class Clone
  6. {
  7. public static T DeepCopy<T>(T source)
  8. {
  9. if (!typeof(T).IsSerializable)
  10. {
  11. throw new ArgumentException("The type must be serializable.", "source");
  12. }
  13. if (Object.ReferenceEquals(source, null))
  14. {
  15. return default(T);
  16. }
  17. IFormatter formatter = new BinaryFormatter();
  18. Stream stream = new MemoryStream();
  19. using (stream)
  20. {
  21. formatter.Serialize(stream, source);
  22. stream.Seek(0, SeekOrigin.Begin);
  23. return (T)formatter.Deserialize(stream);
  24. }
  25. }
  26. }