/src/LinFu.Proxy/ProxyCacheEntry.cs

http://github.com/philiplaureano/LinFu · C# · 78 lines · 50 code · 15 blank · 13 comment · 21 complexity · 8d26e5ad9c789b8f96685c373c685484 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. namespace LinFu.Proxy
  4. {
  5. /// <summary>
  6. /// Represents a cached proxy type.
  7. /// </summary>
  8. internal class ProxyCacheEntry
  9. {
  10. public Type BaseType;
  11. public Type[] Interfaces;
  12. internal ProxyCacheEntry(Type baseType, Type[] interfaces)
  13. {
  14. BaseType = baseType;
  15. Interfaces = interfaces;
  16. }
  17. internal class EqualityComparer : IEqualityComparer<ProxyCacheEntry>
  18. {
  19. public bool Equals(ProxyCacheEntry x, ProxyCacheEntry y)
  20. {
  21. // Match the base t ypes
  22. if (y.BaseType != x.BaseType)
  23. return false;
  24. // If two types have the same base class and
  25. // no interface, then we have a match
  26. if (x.Interfaces.Length == 0 && y.Interfaces.Length == 0)
  27. return true;
  28. // If one set of interfaces is null and the other one is not
  29. // null, then there is no match
  30. if (x.Interfaces == null && y.Interfaces != null ||
  31. y.Interfaces == null && x.Interfaces != null)
  32. return false;
  33. // Initialize both interface lists and
  34. // set them up for comparison
  35. var interfaceList = new HashSet<Type>();
  36. var targetList = new List<Type>();
  37. if (x.Interfaces != null && x.Interfaces.Length > 0)
  38. targetList.AddRange(x.Interfaces);
  39. if (y.Interfaces != null)
  40. interfaceList = new HashSet<Type>(y.Interfaces);
  41. // The length of the interfaces must match
  42. if (interfaceList.Count != targetList.Count)
  43. return false;
  44. foreach (var current in targetList)
  45. if (!interfaceList.Contains(current))
  46. return false;
  47. return true;
  48. }
  49. public int GetHashCode(ProxyCacheEntry obj)
  50. {
  51. var extractor = new InterfaceExtractor();
  52. var types = new HashSet<Type>(obj.Interfaces);
  53. extractor.GetInterfaces(obj.BaseType, types);
  54. // HACK: Calculate the hash code
  55. // by XORing all the types together
  56. var baseType = obj.BaseType;
  57. var result = baseType.GetHashCode();
  58. foreach (var type in types) result ^= type.GetHashCode();
  59. return result;
  60. }
  61. }
  62. }
  63. }