code_junkie

How to perform a deep copy of an object not marked as serializable (in C#)?

Nov 11th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. public IDataObject GetClipboardData()
  2. {
  3. MemoryStream memoryStream = new MemoryStream();
  4. BinaryFormatter binaryFormatter = new BinaryFormatter();
  5. binaryFormatter.Serialize(memoryStream, Clipboard.GetDataObject());
  6. memoryStream.Position = 0;
  7. return (IDataObject) binaryFormatter.Deserialize(memoryStream);
  8. }
  9.  
  10. public static class GhettoSerializer
  11. {
  12. // you could make this a factory method if your type
  13. // has a constructor that appeals to you (i.e. default
  14. // parameterless constructor)
  15. public static void Initialize<T>(T instance, IDictionary<string, object> values)
  16. {
  17. var props = typeof(T).GetProperties();
  18.  
  19. // my approach does nothing to handle rare properties with array indexers
  20. var matches = props.Join(
  21. values,
  22. pi => pi.Name,
  23. kvp => kvp.Key,
  24. (property, kvp) =>
  25. new {
  26. Set = new Action<object,object,object[]>(property.SetValue),
  27. kvp.Value
  28. }
  29. );
  30.  
  31. foreach (var match in matches)
  32. match.Set(instance, match.Value, null);
  33. }
  34. public static IDictionary<string, object> Serialize<T>(T instance)
  35. {
  36. var props = typeof(T).GetProperties();
  37.  
  38. var ret = new Dictionary<string, object>();
  39.  
  40. foreach (var property in props)
  41. {
  42. if (!property.CanWrite || !property.CanRead)
  43. continue;
  44. ret.Add(property.Name, property.GetValue(instance, null));
  45. }
  46.  
  47. return ret;
  48. }
  49. }
Add Comment
Please, Sign In to add comment