Extensions.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Runtime.CompilerServices;
  6. namespace Chronos.Reflection.Internal
  7. {
  8. public static class Extensions
  9. {
  10. /// <summary>
  11. /// Finds the intersection of a group of groups.
  12. /// </summary>
  13. public static IEnumerable<T> IntersectAll<T>(this IEnumerable<IEnumerable<T>> groups)
  14. {
  15. HashSet<T> hashSet = null;
  16. foreach (IEnumerable<T> group in groups)
  17. {
  18. if (hashSet == null)
  19. {
  20. hashSet = new HashSet<T>(group);
  21. }
  22. else
  23. {
  24. hashSet.IntersectWith(group);
  25. }
  26. }
  27. return hashSet == null ? Enumerable.Empty<T>() : hashSet.AsEnumerable();
  28. }
  29. /// <summary>
  30. /// Determines if an enum has the given flag defined bitwise.
  31. /// Fallback equivalent to .NET's Enum.HasFlag().
  32. /// </summary>
  33. public static bool HasFlag(this Enum value, Enum flag)
  34. {
  35. long lValue = Convert.ToInt64(value);
  36. long lFlag = Convert.ToInt64(flag);
  37. return (lValue & lFlag) != 0;
  38. }
  39. #if !NETFX_CORE
  40. private static MethodInfo[] extensionMethodsCache;
  41. /// <summary>
  42. /// Searches all assemblies for extension methods for a given type.
  43. /// </summary>
  44. public static IEnumerable<MethodInfo> GetExtensionMethods(this Type type)
  45. {
  46. // http://stackoverflow.com/a/299526
  47. if (extensionMethodsCache == null)
  48. {
  49. extensionMethodsCache = AppDomain.CurrentDomain.GetAssemblies()
  50. .SelectMany(assembly => assembly.GetTypes())
  51. .Where(potentialType => potentialType.IsSealed && !potentialType.IsGenericType && !potentialType.IsNested)
  52. .SelectMany(extensionType => extensionType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
  53. .Where(method => method.IsExtension())
  54. .ToArray();
  55. }
  56. return extensionMethodsCache.Where(method => method.GetParameters()[0].ParameterType.IsAssignableFrom(type));
  57. }
  58. #endif
  59. public static bool IsExtension(this MethodInfo methodInfo)
  60. {
  61. return methodInfo.IsDefined(typeof(ExtensionAttribute), false);
  62. }
  63. }
  64. }