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

相等性比较

用于自定义对象相等性比较和hash码计算的机制。

1
2
3
4
5
6
7
8
9
10
11
12
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\IEqualityComparer.cs
namespace System.Collections
{
public interface IEqualityComparer
{
// 判断两个对象 x 和 y 是否相等
bool Equals(object? x, object? y);

// 需遵循 “相等的对象必须返回相同哈希码” 的原则(反之不要求)
int GetHashCode(object obj);
}
}

对应的泛型接口:

1
2
3
4
5
6
7
8
9
10
11
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IEqualityComparer.cs
using System.Diagnostics.CodeAnalysis;

namespace System.Collections.Generic
{
public interface IEqualityComparer<in T>
{
bool Equals(T? x, T? y);
int GetHashCode([DisallowNull] T obj);
}
}

基于相等性的比较:

1
2
3
4
5
6
7
8
9
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IStructuralEquatable.cs
namespace System.Collections
{
public interface IStructuralEquatable
{
bool Equals(object? other, IEqualityComparer comparer);
int GetHashCode(IEqualityComparer comparer);
}
}
上一篇:
枚举器
下一篇:
比较