CaseInsensitiveHashCodeProvider.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. //
  2. // System.Collections.CaseInsensitiveHashCodeProvider
  3. //
  4. // Author:
  5. // Sergey Chaban ([email protected])
  6. //
  7. using System;
  8. using System.Collections;
  9. using System.Globalization;
  10. namespace System.Collections {
  11. [Serializable]
  12. public class CaseInsensitiveHashCodeProvider : IHashCodeProvider {
  13. private static CaseInsensitiveHashCodeProvider singleton;
  14. private static CaseInsensitiveHashCodeProvider singletonInvariant;
  15. CultureInfo culture;
  16. // Class constructor
  17. static CaseInsensitiveHashCodeProvider ()
  18. {
  19. singleton = new CaseInsensitiveHashCodeProvider ();
  20. singletonInvariant = new CaseInsensitiveHashCodeProvider (CultureInfo.InvariantCulture);
  21. }
  22. // Public instance constructor
  23. public CaseInsensitiveHashCodeProvider ()
  24. {
  25. }
  26. public CaseInsensitiveHashCodeProvider (CultureInfo culture)
  27. {
  28. this.culture = culture;
  29. }
  30. //
  31. // Public static properties
  32. //
  33. public static CaseInsensitiveHashCodeProvider Default {
  34. get {
  35. return singleton;
  36. }
  37. }
  38. #if NET_1_1
  39. public static CaseInsensitiveHashCodeProvider DefaultInvariant {
  40. get {
  41. return singletonInvariant;
  42. }
  43. }
  44. #endif
  45. //
  46. // Instance methods
  47. //
  48. //
  49. // IHashCodeProvider
  50. //
  51. public int GetHashCode (object obj)
  52. {
  53. if (obj == null) {
  54. throw new ArgumentNullException ("obj is null");
  55. }
  56. string str = obj as string;
  57. if (str == null)
  58. return obj.GetHashCode ();
  59. int h = 0;
  60. char c;
  61. int length = str.Length;
  62. if (culture != null) {
  63. for (int i = 0;i<length;i++) {
  64. c = Char.ToLower (str [i], culture);
  65. h = h * 31 + c;
  66. }
  67. }
  68. else {
  69. for (int i = 0;i<length;i++) {
  70. c = Char.ToLower (str [i]);
  71. h = h * 31 + c;
  72. }
  73. }
  74. return h;
  75. }
  76. } // CaseInsensitiveHashCodeProvider
  77. }