C# 集合类型的默认相等比较器是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17224940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:53:07  来源:igfitidea点击:

What is the default equality comparer for a set type?

c#

提问by John Threepwood

In the MSDN API for the HashSetconstructor with no arguments it states

HashSet没有参数的构造函数的 MSDN API 中,它声明

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

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

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

集合类型(例如自定义类)的默认相等比较器是什么?

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.

顺便说一句:只是我还是 MSDN API 文档的解释真的有点少?我在阅读它时不止一次偶然发现这些问题。

采纳答案by Lee

It means it will use the comparer returned by EqualityComparer<T>.Defaultfor the element type Tof the set.

这意味着它将使用返回的比较器作为集合EqualityComparer<T>.Default的元素类型T

As the documentation states:

正如文档所述:

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.

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

So for your custom type, it will use the GetHashCodemethod 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 objectclass. Therefore if you are defining equality using either method, you should ensure you also override GetHashCodeas well.

因此,对于您的自定义类型,它将使用GetHashCode您定义的方法来定位集合中的项目。如果您已经实现IEquatable<T>,它将IEquatable<T>.Equals(T)用于相等,否则它将使用您的Equals(object)方法。此方法默认引用object类中定义的相等性。因此,如果您使用任一方法定义相等性,则应确保也覆盖GetHashCode

回答by adrianbanks

By default, it will delegate to EqualityComparer<T>.Default. This returns a comparer that can compare two objects of type T.

默认情况下,它将委托给EqualityComparer<T>.Default. 这将返回一个比较器,可以比较两个类型的对象T

For a custom class, this does a few things in this order:

对于自定义类,它按以下顺序执行一些操作:

  • if the class implements IEquatable<T>, it will delegate to the class's implementation of this interface
  • if the class has an Equalsmethod defined, it will use that
  • as a last resort, it will use reference equality
  • 如果类实现了IEquatable<T>,它将委托给类的这个接口的实现
  • 如果该类Equals定义了一个方法,它将使用该方法
  • 作为最后的手段,它将使用引用相等