为什么我们需要的IEqualityComparer,的IEqualityComparer< T>接口?接口、IEqualityComparer、LT、GT

2023-09-03 17:14:28 作者:初心

在平等和GetHash code'的方法是存在的对象类,我们的类继承的对象基类。 什么是直接实现对象的两种方法,并使用IComparer接口之间有什么不同?

the 'Equal' and 'GetHashcode' method are exist in the object class, and our type inherit the object base class. what's the different between implement the two methods of the object directly and using the IComparer interface?

如果我们覆盖对象的平等和GetHash code,并推到一个哈希表,它将使用overring的平等的方法?

if we overriding object's Equal and GetHashCode , and push to a hashtable , it will use the overring 's equal method?

有什么新的哈希表用的IEqualityComparer构造型动物?

what' the differents of new a hashtable with the IEqualityComparer constructor?

推荐答案

IComparable的接口是用来当你需要能够之类的对象,它给你的方法(的CompareTo ),告诉你,如果两个对象是与LT,=或>。使用构造的IEqualityComparer 让你给一个特定的等于 / GetHash code ,可以比你的对象中定义的不同。通常情况下,的Hashtable 将使用您的对象覆盖等于 GetHash code (或基对象 等于 GetHash code )。

The IComparable interface is used when you need to be able to "sort" objects, and it gives you a method (CompareTo) that tells you if two objects are <, = or > . The constructor that uses IEqualityComparer let you give a specific Equals/GetHashCode that can be different than the ones defined by your object. Normally the Hashtable will use your object overridden Equals and GetHashCode (or the base object Equals and GetHashCode).

要做出表率,标准字符串的情况下比较敏感的方式(A!= ),但你可以把一个的IEqualityComparer 辅助类要能散列的字符串,不区分大小写的方式。 (技术上这个类是已经present多个变种:他们被称为 StringComparer.InvariantCultureIgnoreCase StringComparer 返回一个 StringComparer 对象实现了的IComparer 的IEqualityComparer 的IComparer&LT;字符串&GT; 的IEqualityComparer&LT;字符串&GT;

To make an example, the standard string compares in case sensitive way ("A" != "a"), but you could make an IEqualityComparer helper class to be able to hash your strings in a case insensitive way. (technically this class is already present in multiple variants: they are called StringComparer.InvariantCultureIgnoreCase and all the other static methods of StringComparer that return a StringComparer object that implements the IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>)

作为一个说明,在的Hashtable 使用的IEqualityComparer 可选参数,而不是通用版本的IEqualityComparer&LT; T&GT; ,因为的Hashtable 是pre-泛型

As a note, the Hashtable uses a IEqualityComparer optional parameter, not the generic version IEqualityComparer<T>, because Hashtable is pre-generics.