Comparer 类

定义

比较两个对象是否相等,其中字符串比较是区分大小写的。

public sealed class Comparer : System.Collections.IComparer
public sealed class Comparer : System.Collections.IComparer, System.Runtime.Serialization.ISerializable
[System.Serializable]
public sealed class Comparer : System.Collections.IComparer, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Comparer : System.Collections.IComparer, System.Runtime.Serialization.ISerializable
继承
Comparer
属性
实现

示例

下面的代码示例演示如何 Compare 根据与 Comparer关联的区域性返回不同的值。

using System;
using System.Collections;
using System.Globalization;

public class SamplesComparer  {

   public static void Main()  {

      // Creates the strings to compare.
      String str1 = "llegar";
      String str2 = "lugar";
      Console.WriteLine( "Comparing \"{0}\" and \"{1}\" ...", str1, str2 );

      // Uses the DefaultInvariant Comparer.
      Console.WriteLine( "   Invariant Comparer: {0}", Comparer.DefaultInvariant.Compare( str1, str2 ) );

      // Uses the Comparer based on the culture "es-ES" (Spanish - Spain, international sort).
      Comparer myCompIntl = new Comparer( new CultureInfo( "es-ES", false ) );
      Console.WriteLine( "   International Sort: {0}", myCompIntl.Compare( str1, str2 ) );

      // Uses the Comparer based on the culture identifier 0x040A (Spanish - Spain, traditional sort).
      Comparer myCompTrad = new Comparer( new CultureInfo( 0x040A, false ) );
      Console.WriteLine( "   Traditional Sort  : {0}", myCompTrad.Compare( str1, str2 ) );
   }
}

/*
This code produces the following output.

Comparing "llegar" and "lugar" ...
   Invariant Comparer: -1
   International Sort: -1
   Traditional Sort  : 1

*/

注解

此类是 接口的默认实现 IComparer 。 类 CaseInsensitiveComparer 是接口的实现, IComparer 该接口执行不区分大小写的字符串比较。 System.Collections.Generic.Comparer<T> 是此类的泛型等效项。

除非另行指定,否则比较过程使用 Thread.CurrentCulture 当前线程的 。 字符串比较可能具有不同的结果,具体取决于区域性。 有关特定于区域性的比较的详细信息,请参阅 System.Globalization 命名空间和 全球化和本地化

构造函数

Comparer(CultureInfo)

使用指定的 Comparer 初始化 CultureInfo 类的新实例。

字段

Default

表示 Comparer 的实例,它与当前线程的 CurrentCulture 关联。 此字段为只读。

DefaultInvariant

表示 Comparer 的实例,它与 InvariantCulture 关联。 此字段为只读。

方法

Compare(Object, Object)

对同一类型的两个对象执行区分大小写的比较,并返回一个值,指示其中一个对象小于、等于还是大于另一个对象。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)
已过时.

用序列化所需的数据填充 SerializationInfo 对象。

GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

另请参阅