Comparer<T> Comparer<T> Comparer<T> Comparer<T> Class

定義

提供基底類別 (Base Class) 用於 IComparer<T> 泛型介面的實作。Provides a base class for implementations of the IComparer<T> generic interface.

generic <typename T>
public ref class Comparer abstract : System::Collections::Generic::IComparer<T>, System::Collections::IComparer
[System.Serializable]
public abstract class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer
type Comparer<'T> = class
    interface IComparer
    interface IComparer<'T>
Public MustInherit Class Comparer(Of T)
Implements IComparer, IComparer(Of T)

類型參數

T

要比較之物件的類型。The type of objects to compare.

繼承
Comparer<T>Comparer<T>Comparer<T>Comparer<T>
屬性
實作

範例

下列範例會Comparer<T>從類別衍生類別BoxLengthFirstThe following example derives a class, BoxLengthFirst, from the Comparer<T> class. 這個比較子會比較類型Box的兩個物件。This comparer compares two objects of type Box. 它會先依長度排序, 然後依高度和寬度進行排序。It sorts them first by length, then by height, and then by width. 類別會執行介面,Box以控制兩個物件之間的預設比較。 IComparable<T> BoxThe Box class implements the IComparable<T> interface to control the default comparison between two Box objects. 這個預設的實值會先依高度排序, 然後依據長度和寬度進行排序。This default implementation sorts first by height, then by length, and then by width. 此範例會先Box BoxLengthFirst使用比較子來排序物件清單, 然後再使用預設的比較子, 以顯示這兩個比較之間的差異。The example shows the differences between the two comparisons by sorting a list of Box objects first by using the BoxLengthFirst comparer and then by using the default comparer.

using System;
using System.Collections;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<Box> Boxes = new List<Box>();
        Boxes.Add(new Box(4, 20, 14));
        Boxes.Add(new Box(12, 12, 12));
        Boxes.Add(new Box(8, 20, 10));
        Boxes.Add(new Box(6, 10, 2));
        Boxes.Add(new Box(2, 8, 4));
        Boxes.Add(new Box(2, 6, 8));
        Boxes.Add(new Box(4, 12, 20));
        Boxes.Add(new Box(18, 10, 4));
        Boxes.Add(new Box(24, 4, 18));
        Boxes.Add(new Box(10, 4, 16));
        Boxes.Add(new Box(10, 2, 10));
        Boxes.Add(new Box(6, 18, 2));
        Boxes.Add(new Box(8, 12, 4));
        Boxes.Add(new Box(12, 10, 8));
        Boxes.Add(new Box(14, 6, 6));
        Boxes.Add(new Box(16, 6, 16));
        Boxes.Add(new Box(2, 8, 12));
        Boxes.Add(new Box(4, 24, 8));
        Boxes.Add(new Box(8, 6, 20));
        Boxes.Add(new Box(18, 18, 12));

        // Sort by an Comparer<T> implementation that sorts
        // first by the length.
        Boxes.Sort(new BoxLengthFirst());

        Console.WriteLine("H - L - W");
        Console.WriteLine("==========");
        foreach (Box bx in Boxes)
        {
            Console.WriteLine("{0}\t{1}\t{2}",
                bx.Height.ToString(), bx.Length.ToString(), 
                bx.Width.ToString());
        }

        Console.WriteLine();
        Console.WriteLine("H - L - W"); 
        Console.WriteLine("==========");

        // Get the default comparer that 
        // sorts first by the height.
        Comparer<Box> defComp = Comparer<Box>.Default;

        // Calling Boxes.Sort() with no parameter
        // is the same as calling Boxs.Sort(defComp)
        // because they are both using the default comparer.
        Boxes.Sort();

        foreach (Box bx in Boxes)
        {
            Console.WriteLine("{0}\t{1}\t{2}",
                bx.Height.ToString(), bx.Length.ToString(), 
                bx.Width.ToString());
        }


        // This explicit interface implementation
        // compares first by the length.
        // Returns -1 because the length of BoxA
        // is less than the length of BoxB.
        BoxLengthFirst LengthFirst = new BoxLengthFirst(); 

        Comparer<Box> bc = (Comparer<Box>) LengthFirst;

        Box BoxA = new Box(2, 6, 8);
        Box BoxB = new Box(10, 12, 14);
        int x = LengthFirst.Compare(BoxA, BoxB);
        Console.WriteLine();
        Console.WriteLine(x.ToString());

    

    }

}

public class BoxLengthFirst : Comparer<Box> 
{
    // Compares by Length, Height, and Width.
    public override int Compare(Box x, Box y)
    {
        if (x.Length.CompareTo(y.Length) != 0)
        {
            return x.Length.CompareTo(y.Length);
        }
        else if (x.Height.CompareTo(y.Height) != 0)
        {
            return x.Height.CompareTo(y.Height);
        }
        else if (x.Width.CompareTo(y.Width) != 0)
        {
            return x.Width.CompareTo(y.Width);
        }
        else
        {
            return 0;
        }
    }

}

// This class is not demonstrated in the Main method
// and is provided only to show how to implement
// the interface. It is recommended to derive
// from Comparer<T> instead of implementing IComparer<T>.
public class BoxComp : IComparer<Box>
{
    // Compares by Height, Length, and Width.
    public int Compare(Box x, Box y)
    {
        if (x.Height.CompareTo(y.Height) != 0)
        {
            return x.Height.CompareTo(y.Height);
        }
        else if (x.Length.CompareTo(y.Length) != 0)
        {
            return x.Length.CompareTo(y.Length);
        }
        else if (x.Width.CompareTo(y.Width) != 0)
        {
            return x.Width.CompareTo(y.Width);
        }
        else
        {
            return 0;
        }
    }
}

public class Box : IComparable<Box>
{

    public Box(int h, int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }
    public int Height { get; private set; }
    public int Length { get; private set; }
    public int Width { get; private set; }

    public int CompareTo(Box other)
    {
        // Compares Height, Length, and Width.
        if (this.Height.CompareTo(other.Height) != 0)
        {
            return this.Height.CompareTo(other.Height);
        }
        else if (this.Length.CompareTo(other.Length) != 0)
        {
            return this.Length.CompareTo(other.Length);
        }
        else if (this.Width.CompareTo(other.Width) != 0)
        {
            return this.Width.CompareTo(other.Width);
        }
        else
        {
            return 0;
        }
    }

}

Imports System.Collections.Generic

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim Boxes As New List(Of Box)()
		Boxes.Add(New Box(4, 20, 14))
		Boxes.Add(New Box(12, 12, 12))
		Boxes.Add(New Box(8, 20, 10))
		Boxes.Add(New Box(6, 10, 2))
		Boxes.Add(New Box(2, 8, 4))
		Boxes.Add(New Box(2, 6, 8))
		Boxes.Add(New Box(4, 12, 20))
		Boxes.Add(New Box(18, 10, 4))
		Boxes.Add(New Box(24, 4, 18))
		Boxes.Add(New Box(10, 4, 16))
		Boxes.Add(New Box(10, 2, 10))
		Boxes.Add(New Box(6, 18, 2))
		Boxes.Add(New Box(8, 12, 4))
		Boxes.Add(New Box(12, 10, 8))
		Boxes.Add(New Box(14, 6, 6))
		Boxes.Add(New Box(16, 6, 16))
		Boxes.Add(New Box(2, 8, 12))
		Boxes.Add(New Box(4, 24, 8))
		Boxes.Add(New Box(8, 6, 20))
		Boxes.Add(New Box(18, 18, 12))

		' Sort by an Comparer<T> implementation that sorts
		' first by the length.
		Boxes.Sort(New BoxLengthFirst())

		Console.WriteLine("H - L - W")
		Console.WriteLine("==========")
		For Each bx As Box In Boxes
            Console.WriteLine("{0}" & vbTab & "{1}" & vbTab & "{2}", _
                              bx.Height.ToString(), bx.Length.ToString(), _
                              bx.Width.ToString())
		Next bx

		Console.WriteLine()
		Console.WriteLine("H - L - W")
		Console.WriteLine("==========")

		' Get the default comparer that 
		' sorts first by the height.
		Dim defComp As Comparer(Of Box) = Comparer(Of Box).Default

		' Calling Boxes.Sort() with no parameter
		' is the same as calling Boxs.Sort(defComp)
		' because they are both using the default comparer.
		Boxes.Sort()

		For Each bx As Box In Boxes
            Console.WriteLine("{0}" & vbTab & "{1}" & vbTab & "{2}", _
                              bx.Height.ToString(), _
                              bx.Length.ToString(), _
                              bx.Width.ToString())
		Next bx


		' This explicit interface implementation
		' compares first by the length.
		' Returns -1 because the length of BoxA
		' is less than the length of BoxB.
		Dim LengthFirst As New BoxLengthFirst()

		Dim bc As Comparer(Of Box) = CType(LengthFirst, Comparer(Of Box))

		Dim BoxA As New Box(2, 6, 8)
		Dim BoxB As New Box(10, 12, 14)
		Dim x As Integer = LengthFirst.Compare(BoxA, BoxB)
		Console.WriteLine()
		Console.WriteLine(x.ToString())



	End Sub

End Class

Public Class BoxLengthFirst
	Inherits Comparer(Of Box)
	' Compares by Length, Height, and Width.
	Public Overrides Function Compare(ByVal x As Box, ByVal y As Box) As Integer
		If x.Length.CompareTo(y.Length) <> 0 Then
			Return x.Length.CompareTo(y.Length)
		ElseIf x.Height.CompareTo(y.Height) <> 0 Then
			Return x.Height.CompareTo(y.Height)
		ElseIf x.Width.CompareTo(y.Width) <> 0 Then
			Return x.Width.CompareTo(y.Width)
		Else
			Return 0
		End If
	End Function

End Class

' This class is not demonstrated in the Main method
' and is provided only to show how to implement
' the interface. It is recommended to derive
' from Comparer<T> instead of implementing IComparer<T>.
Public Class BoxComp
	Implements IComparer(Of Box)
	' Compares by Height, Length, and Width.
    Public Function Compare(ByVal x As Box, ByVal y As Box) As Integer Implements _
                                                IComparer(Of Box).Compare
        If x.Height.CompareTo(y.Height) <> 0 Then
            Return x.Height.CompareTo(y.Height)
        ElseIf x.Length.CompareTo(y.Length) <> 0 Then
            Return x.Length.CompareTo(y.Length)
        ElseIf x.Width.CompareTo(y.Width) <> 0 Then
            Return x.Width.CompareTo(y.Width)
        Else
            Return 0
        End If
    End Function
End Class

Public Class Box
	Implements IComparable(Of Box)

	Public Sub New(ByVal h As Integer, ByVal l As Integer, ByVal w As Integer)
		Me.Height = h
		Me.Length = l
		Me.Width = w
	End Sub
	Private privateHeight As Integer
	Public Property Height() As Integer
		Get
			Return privateHeight
		End Get
		Private Set(ByVal value As Integer)
			privateHeight = value
		End Set
	End Property
	Private privateLength As Integer
	Public Property Length() As Integer
		Get
			Return privateLength
		End Get
		Private Set(ByVal value As Integer)
			privateLength = value
		End Set
	End Property
	Private privateWidth As Integer
	Public Property Width() As Integer
		Get
			Return privateWidth
		End Get
		Private Set(ByVal value As Integer)
			privateWidth = value
		End Set
	End Property

    Public Function CompareTo(ByVal other As Box) As Integer _
                        Implements IComparable(Of Box).CompareTo
        ' Compares Height, Length, and Width.
        If Me.Height.CompareTo(other.Height) <> 0 Then
            Return Me.Height.CompareTo(other.Height)
        ElseIf Me.Length.CompareTo(other.Length) <> 0 Then
            Return Me.Length.CompareTo(other.Length)
        ElseIf Me.Width.CompareTo(other.Width) <> 0 Then
            Return Me.Width.CompareTo(other.Width)
        Else
            Return 0
        End If
    End Function

End Class

備註

衍生自這個類別, 以提供IComparer<T>介面的自訂執行, 以便與SortedList<TKey,TValue>SortedDictionary<TKey,TValue>泛型類別之類的集合類別搭配使用。Derive from this class to provide a custom implementation of the IComparer<T> interface for use with collection classes such as the SortedList<TKey,TValue> and SortedDictionary<TKey,TValue> generic classes.

衍生自Comparer<T>類別和System.IComparable執行介面的差異如下所示:The difference between deriving from the Comparer<T> class and implementing the System.IComparable interface is as follows:

  • 若要指定預設應如何比較兩個物件, 請在System.IComparable您的類別中執行介面。To specify how two objects should be compared by default, implement the System.IComparable interface in your class. 這可確保排序作業會使用您所提供的預設比較程式碼。This ensures that sort operations will use the default comparison code that you provided.

  • 若要定義要使用的比較子, 而不是預設的比較Comparer<T>子, 請從類別衍生。To define a comparer to use instead of the default comparer, derive from the Comparer<T> class. 接著, 您可以在採用比較子做為參數的排序作業中使用這個比較子。You can then use this comparer in sort operations that take a comparer as a parameter.

Default屬性所傳回的物件會System.IComparable<T>使用IComparable<T> C#泛型介面 (在VisualBasic中)來比較兩個物件。IComparable(Of T)The object returned by the Default property uses the System.IComparable<T> generic interface (IComparable<T> in C#, IComparable(Of T) in Visual Basic) to compare two objects. 如果類型T System.IComparable<T>未執行泛型介面Default , 屬性會傳回使用System.IComparable介面的。 Comparer<T>If type T does not implement the System.IComparable<T> generic interface, the Default property returns a Comparer<T> that uses the System.IComparable interface.

給繼承者的注意事項

System.Collections.Generic.Comparer`1.Compare(\`0,`0)System.Collections.Generic.EqualityComparer`1.Equals(\`0,\`0)的行為可能會因文化特性區分和區分大小寫而有所不同。 System.Collections.Generic.Comparer`1.Compare(`0,\`0) and System.Collections.Generic.EqualityComparer`1.Equals(`0,\`0) may behave differently in terms of culture-sensitivity and case-sensitivity.

針對字串比較, StringComparer建議您透過比較<子字串>來使用類別。For string comparisons, the StringComparer class is recommended over Comparer<String>. StringComparer類別的屬性會傳回預先定義的實例, 其會以區分文化特性和區分大小寫的不同組合來執行字串比較。Properties of the StringComparer class return predefined instances that perform string comparisons with different combinations of culture-sensitivity and case-sensitivity. 區分大小寫和區分文化特性, 在相同StringComparer實例的成員之間是一致的。The case-sensitivity and culture-sensitivity are consistent among the members of the same StringComparer instance.

如需有關文化特性特定比較的詳細資訊, System.Globalization請參閱命名空間和全球化和當地語系化For more information on culture-specific comparisons, see the System.Globalization namespace and Globalization and Localization.

建構函式

Comparer<T>() Comparer<T>() Comparer<T>() Comparer<T>()

初始化 Comparer<T> 類別的新執行個體。Initializes a new instance of the Comparer<T> class.

屬性

Default Default Default Default

傳回泛型引數指定之型別的預設排序次序比較子 (Comparer)。Returns a default sort order comparer for the type specified by the generic argument.

方法

Compare(T, T) Compare(T, T) Compare(T, T) Compare(T, T)

在衍生類別中覆寫時,比較型別相同的兩個物件並傳回值,指出一個物件是小於、等於還是大於另一個物件。When overridden in a derived class, performs a comparison of two objects of the same type and returns a value indicating whether one object is less than, equal to, or greater than the other.

Create(Comparison<T>) Create(Comparison<T>) Create(Comparison<T>) Create(Comparison<T>)

使用指定的比較建立比較子。Creates a comparer by using the specified comparison.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)

明確介面實作

IComparer.Compare(Object, Object) IComparer.Compare(Object, Object) IComparer.Compare(Object, Object) IComparer.Compare(Object, Object)

比較兩個物件並傳回值,指出其中一個物件為小於、等於或大於另一個物件。Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.

適用於

另請參閱