TypeExtensionMethod.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace VCommon.Reflection
  6. {
  7. public static class TypeExtensionMethod
  8. {
  9. /// <summary> 获取该类所有公开实例属性 </summary>
  10. public static PropertyInfo[] GetPublicInstanceProperties(this Type type) => type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  11. /// <summary> 获取该类所有公开实例字段 </summary>
  12. public static FieldInfo[] GetPublicInstanceFields(this Type type) => type.GetFields(BindingFlags.Public | BindingFlags.Instance);
  13. /// <summary> 获取全部公开实例方法 </summary>
  14. public static MethodInfo[] GetPublicInstanceMethods(this Type type) => type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
  15. /// <summary>
  16. /// 反射一个类的全部接口, 按提供的类过滤, 支持泛型, 将匹配的不同泛型分组返回, 另外提供未命中的接口
  17. /// </summary>
  18. public static IReadOnlyDictionary<Type, Type[]> FilterInterfaces(this Type type, Type[] interfacesToCheck, out Type[] noMatches)
  19. {
  20. var riface = type.GetInterfaces();
  21. var lstNoMatches = new HashSet<Type>();
  22. var dic = new Dictionary<Type, Type[]>();
  23. foreach (var check in interfacesToCheck)
  24. {
  25. var list = new List<Type>();
  26. foreach (var ri in riface)
  27. {
  28. if (ri == check)
  29. {
  30. list.Add(ri);
  31. }
  32. else if (ri.IsGenericType)
  33. {
  34. var genericTypeDefinition = ri.GetGenericTypeDefinition();
  35. if (genericTypeDefinition == check)
  36. {
  37. list.Add(ri);
  38. }
  39. else if (false == interfacesToCheck.Contains(genericTypeDefinition))
  40. {
  41. lstNoMatches.Add(ri);
  42. }
  43. }
  44. else if (false == interfacesToCheck.Contains(ri))
  45. {
  46. lstNoMatches.Add(ri);
  47. }
  48. }
  49. if (0 == list.Count) continue;
  50. dic[check] = list.ToArray();
  51. }
  52. noMatches = lstNoMatches.ToArray();
  53. return dic;
  54. }
  55. }
  56. }