问题描述
这是任何不同于CLR的角度来看,以实施的IEqualityComparer
VS覆盖 ==
运营商的财产,你在将使用的IEqualityComparer< T>
?如果是这样,当你使用一个对其他?
Is it any different from the CLR standpoint to implement IEqualityComparer
vs overriding the ==
operator for the property you would use in the IEqualityComparer<T>
? And if so, when would you use one against the other?
修改
确定它有一定道理所使用的哈希表的实现中IEqaulityComparer - 它溜出了我的脑海,当我张贴的问题。那么,关于IEnumerable的的LINQ的的扩展。这是否意味着执行这些类型的扩展方法时.NET建立了一个哈希表?
Ok it does make sense that the IEqaulityComparer used by the implementations of Hashtable - it slipped out of my mind when I was posting the question. So what about the extensions of Linq of IEnumerable. Does that mean that .net builds up a Hashtable when executing those kind of extension methods?
推荐答案
的IEqualityComparer
不是等于
,等于为为对象(例如方法),但EqualityComparer是在LINQ的装饰,比如你想要做具体的不同的:
IEqualityComparer
is not equal
, equal is for object (instance method) but EqualityComparer is for decoration for example in linq you want do specific distinct:
personList.OrderBy(P =&GT; p.ID).Distinct(新MyEqualityComparer())
和
class MyEqualityComparer: IEqualityComparer<Person>
{
public bool Equals(Person p1, Person p2)
{
if (p1.Age == p2.Age)
return true;
return false;
}
public int GetHashCode(Person p)
{
return p.Id.GetHashCode();
}
}
但平等是人:
but equal is for Person:
public class Person
{
public int ID{get;set;}
public int Age{get;set;}
public override bool Equals(object o)
{
//do stuff
}
}
您可以通过的IEqualityComparer做任何数量的装饰,但你不能用实例方法做到这一点(你可以写personList.Distinct(新AnotherComparer),...)
you can do any number of decoration by IEqualityComparer but you can't do this by instance method (you can write personList.Distinct(new AnotherComparer) ,...)
这篇关于比较对象在.net中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!