什么是IEquatable,只是压倒一切的Object.Equals()之间的区别是什么? [英] What's the difference between IEquatable and just overriding Object.Equals()?
问题描述
我希望我的食品类能够测试时,它等于另一个类。稍后我会用它对付一个列表,我想使用它的List.Contains()方法。我应该实现IEquatable或者只是覆盖的Object.Equals()?从MSDN:
I want my Food class to be able to test whenever it is equal to another class. I will later use it against a List, and I want to use its List.Contains() method. Should I implement IEquatable or just override Object.Equals()? From MSDN:
该方法被确定平等 使用默认的相等比较, 由对象的定义 实施 IEquatable.Equals方法对于T (值的列表中的类型)。
This method determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list).
因此,我的下一个问题是:在.NET框架的哪些功能/类使用的Object.Equals()?我应该首先使用它?
So my next question is: which functions/classes of the .NET framework make use of Object.Equals()? Should I use it in the first place?
感谢
推荐答案
主要的原因是性能。当仿制药进行了介绍.NET 2.0中,他们可以添加一堆整齐的类,如名单,其中,T>
,词典< K,V>
,的HashSet< T>
等,这些结构经常使用 GetHash code
和等于
。但对于值类型此要求的拳击。 IEquatable< T>
让结构实现一个强类型等于
方法,所以没有拳击是必需的。因此,更好的性能使用值类型时泛型集合。
The main reason is performance. When generics were introduced in .NET 2.0 they were able to add a bunch of neat classes such as List<T>
, Dictionary<K,V>
, HashSet<T>
, etc. These structures make heavy use of GetHashCode
and Equals
. But for value types this required boxing. IEquatable<T>
lets a structure implement a strongly typed Equals
method so no boxing is required. Thus much better performance when using value types with generic collections.
引用类型不受益很多,但在 IEquatable&LT; T&GT;
的实施确实让你避免从铸 System.Object的
,可以有所作为,如果它经常被称为。
Reference types don't benefit as much but the IEquatable<T>
implementation does let you avoid a cast from System.Object
which can make a difference if it's called frequently.
正如在<一个href="http://blogs.msdn.com/jaredpar/archive/2009/01/15/if-you-implement-iequatable-t-you-still-must-override-object-s-equals-and-gethash$c$c.aspx">Jared帕森斯的博客不过,你仍然必须实现对象覆盖。
As noted on Jared Parson's blog though, you still must implement the Object overrides.
这篇关于什么是IEquatable,只是压倒一切的Object.Equals()之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!