IComparer接口是比较委托,因为IEqualityComparer是什么?

时间:2013-11-28 11:01:22

标签: c# .net

我喜欢Comparison委托,制作一个比IComparer更容易。

IEqualityComparer是否有类似的委托?

IComparer接口是比较委托,因为IEqualityComparer是什么?

2 个答案:

答案 0 :(得分:5)

没有等价物,因为不可能有一个。 IComparer<T>只定义一个成员,因此您可以将其“提炼”为委托。

相比之下,IEqualityComparer<T>必须同时提供EqualsGetHashCode实施,才能普遍有用。您不能将这两者都放入委托中,因此不等同于Comparison<T>

也就是说,直接比较类型T的两个实例的代表的签名是EqualityComparer<T>.Equals给出的 - 即Func<T, T, bool>

答案 1 :(得分:0)

您始终可以实现通用的EqualityComparer:

 public class GenericEqualityComparer<T> : IEqualityComparer<T>
 {
     private Func<T, T, bool> equalsFunction;
     private Func<T, int> getHashCodeFunction;

     public GenericEqualityComparer(Func<T, T, bool> equalsFunction, Func<T, int> getHashCodeFunction)
     {
         this.equalsFunction = equalsFunction;
         this.getHashCodeFunction = getHashCodeFunction;
     }

     public bool Equals(T x, T y)
     {
         return this.equalsFunction(x, y);
     }

     public int GetHashCode(T obj)
     {
         return this.getHashCodeFunction(obj);
     }
 }

并使用它:

var list = new[]{"A","B","C","A"};
var distinct = list.Distinct(
      new GenericEqualityComparer<string>(
             (a,b) => a.Equals(b), 
             a => a.GetHashCode()));