比较
发表于:2025-10-13 | 分类: Dotnet
字数统计: 165 | 阅读时长: 1分钟 | 阅读量:

比较

用于实现两个对象的比较逻辑,可以自定义对象的比较规则。

1
2
3
4
5
6
7
8
9
10
11
12
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\IComparer.cs
namespace System.Collections
{
// 实现比较两个对象的方法,用于结合 Array/List 类的 Sort/BinarySearch 方法。
public interface IComparer
{
// <0: x<y
// >0: x>y
// 0: x==y
int Compare(object? x, object? y);
}
}

对应的泛型接口:

1
2
3
4
5
6
7
8
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IComparer.cs
namespace System.Collections.Generic
{
public interface IComparer<in T>
{
int Compare(T? x, T? y);
}
}

基于比较器比较:

1
2
3
4
5
6
7
8
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IStructuralComparable.cs
namespace System.Collections
{
public interface IStructuralComparable
{
int CompareTo(object? other, IComparer comparer);
}
}
上一篇:
相等性比较
下一篇:
枚举