ObjectToDictionaryHelper.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Text;
  5. namespace TEAMModelOS.SDK
  6. {
  7. public static class ObjectToDictionaryHelper
  8. {
  9. public static IDictionary<string, object> ToDictionary(this object source)
  10. {
  11. return source.ToDictionary<object>();
  12. }
  13. public static IDictionary<string, T> ToDictionary<T>(this object source)
  14. {
  15. if (source == null)
  16. ThrowExceptionWhenSourceArgumentIsNull();
  17. var dictionary = new Dictionary<string, T>();
  18. foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
  19. AddPropertyToDictionary<T>(property, source, dictionary);
  20. return dictionary;
  21. }
  22. private static void AddPropertyToDictionary<T>(PropertyDescriptor property, object source, Dictionary<string, T> dictionary)
  23. {
  24. object value = property.GetValue(source);
  25. if (IsOfType<T>(value))
  26. dictionary.Add(property.Name, (T)value);
  27. }
  28. private static bool IsOfType<T>(object value)
  29. {
  30. return value is T;
  31. }
  32. private static void ThrowExceptionWhenSourceArgumentIsNull()
  33. {
  34. throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
  35. }
  36. }
  37. }