ObjectToDictionaryHelper.cs 1.4 KB

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