AttributeExtensionMethod.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Reflection;
  6. namespace VCommon.Reflection
  7. {
  8. public static class AttributeExtensionMethod
  9. {
  10. public static T[] GetCustomAttributeIncludeInterface<T>(this Type findFrom) where T : Attribute
  11. {
  12. var ofType = findFrom.GetCustomAttributes<T>(true);
  13. var ifaces = findFrom.GetInterfaces().SelectMany(i => i.GetCustomAttributes<T>(true));
  14. return ofType.Concat(ifaces).Distinct().ToArray();
  15. }
  16. public static string GetDescriptionAttributeValue(this MemberInfo me) => me.GetCustomAttribute<DescriptionAttribute>()?.Description;
  17. public static bool IsDefinedIncludeInterface(this Type me, Type attributeType) => me.IsDefined(attributeType, true) || me.GetInterfaces().Any(p => p.IsDefined(attributeType, true));
  18. public static bool IsDefinedIncludeInterface(this PropertyInfo me, Type attributeType) => me.IsDefined(attributeType, true) || LookupInterfaceDefines(me, attributeType);
  19. public static T[] GetCustomAttributeIncludeInterface<T>(this PropertyInfo me)
  20. {
  21. var lstResult = new List<T>();
  22. lstResult.AddRange(me.GetCustomAttributes().OfType<T>());
  23. var interfaces = me.DeclaringType?.GetInterfaces();
  24. if (null == interfaces) return lstResult.ToArray();
  25. foreach (var iface in interfaces)
  26. {
  27. var propertyInfo = iface.GetProperty(me.Name);
  28. if (null != propertyInfo) lstResult.AddRange(propertyInfo.GetCustomAttributes(true).OfType<T>());
  29. }
  30. return lstResult.ToArray();
  31. }
  32. private static bool LookupInterfaceDefines(PropertyInfo me, Type attributeType)
  33. {
  34. var interfaces = me?.DeclaringType?.GetInterfaces();
  35. return null != interfaces
  36. && interfaces.Any(p => true == p.GetProperty(me.Name)?.IsDefined(attributeType, true));
  37. }
  38. }
  39. }