Why we need the IEqualityComparer,IEqualityComparer<T> interface?

删除回忆录丶 提交于 2019-12-04 07:09:41

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).

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>)

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

the IComparer interfaces (both the generic and the non-generic one) allow you to compare two instances with each other.

The Compare method allows you to compare an object itself with another instance. Offcourse, when the current instance is null, you'll get a NullReferenceException in this case, since you call Compare on a 'null' instance. A class that implements IComparer can overcome this problem.

So, when you implement the IComparer interface, you'll have a class which has a 'Compare' method, which can be called like this:

public class MyObjectComparer : IComparer<MyObject>
{
    public int Compare( MyObject first, MyObject second )
    {
       // implement logic here to determine whether first is less, greater or equal then second.
    }
}

This allows you to do this:

var c = new MyObjectComparer();
var one = new MyObject();
var two = new MyObject();
c.Compare (one, two);

When you instantiate a Hashtable with the constructor where you specify the IEqualityComparer instance, this means that the given IEqualityComparer will be used to determine whether a certain key is already present in the Hashtable.
Otherwise, the Compare method of the key-object will be used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!