IComparer<T> 接口
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
定义类型为比较两个对象而实现的方法。
generic <typename T>
public interface class IComparer
C#
public interface IComparer<in T>
C#
public interface IComparer<T>
type IComparer<'T> = interface
Public Interface IComparer(Of In T)
Public Interface IComparer(Of T)
- 派生
以下示例实现 接口, IComparer<T> 以根据对象的尺寸比较 类型的 Box
对象。 此示例是为 类提供的更大示例的一 Comparer<T> 部分。
C#
// 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;
}
}
}
' 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
此接口与 List<T>.Sort 和 List<T>.BinarySearch 方法一起使用。 它提供了一种自定义集合的排序顺序的方法。 实现此接口的类包括 SortedDictionary<TKey,TValue> 和 SortedList<TKey,TValue> 泛型类。
此接口的默认实现是 Comparer<T> 类。 类 StringComparer 为类型 String实现此接口。
此接口支持排序比较。 也就是说,当方法返回 0 时 Compare ,这意味着两个对象排序相同。 完全相等比较的实现由 IEqualityComparer<T> 泛型接口提供。
建议派生自 Comparer<T> 类,而不是实现 IComparer<T> 接口,因为 Comparer<T> 类提供 方法的 IComparer.Compare 显式接口实现,以及 Default 获取 对象的默认比较器的属性。
Compare(T, T) |
比较两个对象并返回一个值,该值指示一个对象小于、等于还是大于另一个对象。 |
产品 | 版本 |
---|---|
.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 | 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 | 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1 |
UWP | 10.0 |