.NET HashSet contains 方法的内部实现?

发布于 2024-09-17 10:08:24 字数 190 浏览 1 评论 0原文

我正在为用 C# 编写的库编写测试。我想测试两个列表是否相同当且仅当它们具有相同的元素(不要求元素具有相同的顺序)。我尝试将列表转换为哈希集并检查两个哈希集是否相同。但运行结果并不是我所期望的。

谁能解释一下 hashset contains 方法是如何工作的?它是通过对象的 getHashCode 方法还是 equals 方法比较两个对象?谢谢!

I am writing a test for my library written in C#. And I want to test whether two list are same if and only if they have same elements(do not require elements in the same order). I try to convert list to hashset and check whether the two hashset are same. But the running result is not what I expected.

Could anyone explain how the hashset contains method works? Does it compare two objects by the objects getHashCode method or equals method? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

太阳男子 2024-09-24 10:08:24

它使用 IEqualityComparer<>您传递给 HashSet 构造函数的值。如果您没有通过,那么它将使用 EqualityComparer<>.Default。其中,如果元素类型未实现 IEquatable<>使用该类型的 Equals 和 GetHashCode 方法。

我猜想您的列表包含不会覆盖这些方法的对象。使用 IEqualityComparer 构造函数参数进行修复。

It uses the IEqualityComparer<> that you passed to the HashSet constructor. If you didn't pass one then it uses EqualityComparer<>.Default. Which, if the element type doesn't implement IEquatable<> uses the Equals and GetHashCode methods of the type.

I would guess that your list contains objects that don't override these methods. Use the IEqualityComparer constructor argument to fix.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文