ObjectCopier.cs 669 B

1234567891011121314151617181920212223242526272829
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization;
  4. using System.Runtime.Serialization.Formatters.Binary;
  5. public static class ObjectCopier
  6. {
  7. public static T Clone<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. T result;
  20. using (stream)
  21. {
  22. formatter.Serialize(stream, source);
  23. stream.Seek(0L, SeekOrigin.Begin);
  24. result = (T)((object)formatter.Deserialize(stream));
  25. }
  26. return result;
  27. }
  28. }