开发者

Internal implementation of .NET HashSet contains method?

开发者 https://www.devze.com 2023-01-14 06:27 出处:网络
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

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 h开发者_C百科ow the hashset contains method works? Does it compare two objects by the objects getHashCode method or equals method? Thanks!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消