.net - IEqualityComparer.Equals 与 IEnumerable.Contains 一起使用时,x 或 y 是列表中的值吗?

标签 .net ienumerable iequalitycomparer

IEnumberable 有一个扩展方法 Contains,它带有两个参数。第一个参数是要检查的值,第二个参数是 IEqualityComparer 的实现。 查看 IEqualityComparer.Equals,它需要两个名为 x 和 y 的参数,用于比较第一个和第二个对象。

我的问题是 X 或 Y 是 IEnumerable 中的值?

示例

List<string> test = new List<String() { "a", "b", "c" };
test.Contains("d", myComparer);

当它调用第一个值的 Equals 方法时,它会是 等于(“a”,“d”)还是等于(“d”,“a”)?

最佳答案

这不重要——平等应该是对称的。来自 IEqualityComparer<T>.Equals 的文档:

The Equals method is reflexive, symmetric, and transitive. That is, it returns true if used to compare an object with itself; true for two objects x and y if it is true for y and x; and true for two objects x and z if it is true for x and y and also true for y and z.

我不相信 Enumerable.Contains 中的用法定义明确,即它可能在未来版本中更改。如果您只是让相等比较器遵守接口(interface)文档,那就没问题了。

关于.net - IEqualityComparer.Equals 与 IEnumerable.Contains 一起使用时,x 或 y 是列表中的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/751081/

相关文章:

c# - 为什么 IEqualityComparer<T> 不在 .NET 中扩展 IEqualityComparer

c# - 如何使用 EqualityComparer<T>.Default 的自定义比较器?

c# - 为什么在所有初始订阅者断开连接后 RefCount 不工作? (减少)

c# - 使用 IEnumerable 与 ICollection 与 IList 的自定义集合

c# - OrderBy Linq 的奇怪行为

c# - IEnumerable 泛型的扩展

c# - 在运行时添加文本框并保存更改

c# - 如何在 process.Start() 之后安全地获取进程 Id?

c# - 当尝试将 json 字符串解析为所述对象时,为什么我的对象为 null

.net - 为什么我们需要 IEqualityComparer,IEqualityComparer<T> 接口(interface)?