集合类型的默认相等比较器是什么? [英] What is the default equality comparer for a set type?

查看:147
本文介绍了集合类型的默认相等比较器是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HashSet 的MSDN API中c $ c> 不声明任何参数的构造函数

In the MSDN API for the HashSet constructor with no arguments it states


初始化HashSet类的新实例,该实例为空且
使用默认的相等比较器作为集合类型。

Initializes a new instance of the HashSet class that is empty and uses the default equality comparer for the set type.

设置类型的默认相等比较器是什么,例如

What is the default equality comparer for the set type, e.g. for a custom class?

BTW:是我还是MSDN API文档的解释真的很薄?在阅读它时,我多次遇到这样的问题。

BTW: Is it just me or is the MSDN API documentation really a bit thin on explanations? I stumble about such questions more than once when reading it.

推荐答案

这意味着它将使用EqualityComparer<T>。默认 表示元素类型<集合中的code> T

文档说明:

Default属性检查类型T是否实现
System.IEquatable接口,如果是,则返回使用该实现的
EqualityComparer。否则,它
返回一个EqualityComparer,该重写器使用T提供的
Object.Equals和Object.GetHashCode的覆盖。

The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

因此,对于您的自定义类型,它将使用您定义的 GetHashCode 方法来查找集合中的项目。如果您已实现 IEquatable< T> ,它将使用 IEquatable< T> .Equals(T)进行相等操作,否则它将使用您的 Equals(object)方法。此方法默认引用 object 类中定义的相等性。因此,如果要使用这两种方法定义相等性,则应确保还重写 GetHashCode

So for your custom type, it will use the GetHashCode method you have defined to locate items in the set. If you have implemented IEquatable<T> it will use IEquatable<T>.Equals(T) for equality, otherwise it will use your Equals(object) method. This method defaults to reference equality as defined in the object class. Therefore if you are defining equality using either method, you should ensure you also override GetHashCode as well.

这篇关于集合类型的默认相等比较器是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆