TypePropertyLocator.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace Quadarax.Foundation.Common.Reflection
  6. {
  7. public static class TypePropertyLocator
  8. {
  9. private static readonly IDictionary<string, PropertyInfo> _propertyCache = new Dictionary<string, PropertyInfo>();
  10. public static PropertyInfo GetProperty(this Type type, string propertyName)
  11. {
  12. var key = GetCacheKey(type, propertyName);
  13. if (_propertyCache.ContainsKey(key))
  14. return _propertyCache[key];
  15. var properties = type.GetProperties(BindingFlags.Public | BindingFlags.IgnoreCase);
  16. var property = properties.SingleOrDefault(x => x.Name == propertyName);
  17. if (property!=null)
  18. _propertyCache.Add(key,property);
  19. return property;
  20. }
  21. public static object GetPropertyValue(this Type type, string propertyName, object sourceObject)
  22. {
  23. if (sourceObject==null)
  24. throw new ArgumentNullException(nameof(sourceObject));
  25. var property = type.GetProperty(propertyName);
  26. if (property == null)
  27. throw new ArgumentException($"Property '{propertyName}' doesn't exists in type '{type.Name}'.", nameof(propertyName));
  28. return property.GetValue(sourceObject);
  29. }
  30. public static string GetPropertyValueAsString(this Type type, string propertyName, object sourceObject)
  31. {
  32. var value = type.GetPropertyValue(propertyName, sourceObject);
  33. return value != null? value.ToString() : string.Empty;
  34. }
  35. private static string GetCacheKey(Type type, string propertyName)
  36. {
  37. if (string.IsNullOrEmpty(propertyName))
  38. throw new ArgumentNullException(nameof(propertyName));
  39. return type.FullName + "_" + propertyName;
  40. }
  41. }
  42. }