Comparer.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. /*============================================================
  5. **
  6. ** Purpose: Default IComparer implementation.
  7. **
  8. ===========================================================*/
  9. using System.Globalization;
  10. using System.Runtime.Serialization;
  11. namespace System.Collections
  12. {
  13. [Serializable]
  14. [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  15. public sealed class Comparer : IComparer, ISerializable
  16. {
  17. private CompareInfo _compareInfo;
  18. public static readonly Comparer Default = new Comparer(CultureInfo.CurrentCulture);
  19. public static readonly Comparer DefaultInvariant = new Comparer(CultureInfo.InvariantCulture);
  20. public Comparer(CultureInfo culture)
  21. {
  22. if (culture == null)
  23. throw new ArgumentNullException(nameof(culture));
  24. _compareInfo = culture.CompareInfo;
  25. }
  26. private Comparer(SerializationInfo info, StreamingContext context)
  27. {
  28. if (info == null)
  29. throw new ArgumentNullException(nameof(info));
  30. _compareInfo = (CompareInfo)info.GetValue("CompareInfo", typeof(CompareInfo));
  31. }
  32. public void GetObjectData(SerializationInfo info, StreamingContext context)
  33. {
  34. if (info == null)
  35. throw new ArgumentNullException(nameof(info));
  36. info.AddValue("CompareInfo", _compareInfo);
  37. }
  38. // Compares two Objects by calling CompareTo.
  39. // If a == b, 0 is returned.
  40. // If a implements IComparable, a.CompareTo(b) is returned.
  41. // If a doesn't implement IComparable and b does, -(b.CompareTo(a)) is returned.
  42. // Otherwise an exception is thrown.
  43. //
  44. public int Compare(object a, object b)
  45. {
  46. if (a == b) return 0;
  47. if (a == null) return -1;
  48. if (b == null) return 1;
  49. string sa = a as string;
  50. string sb = b as string;
  51. if (sa != null && sb != null)
  52. return _compareInfo.Compare(sa, sb);
  53. IComparable ia = a as IComparable;
  54. if (ia != null)
  55. return ia.CompareTo(b);
  56. IComparable ib = b as IComparable;
  57. if (ib != null)
  58. return -ib.CompareTo(a);
  59. throw new ArgumentException(SR.Argument_ImplementIComparable);
  60. }
  61. }
  62. }