何时使用IEquatable< T>又为什么 [英] When To Use IEquatable<T> And Why
问题描述
IEquatable< T>是什么?
可以买给您吗?我看到它有用的唯一原因是在创建泛型类型并强迫用户实现和编写良好的equals方法时。
What does IEquatable<T>
buy you, exactly? The only reason I can see it being useful is when creating a generic type and forcing users to implement and write a good equals method.
我缺少什么?
推荐答案
从 MSDN :
IEquatable(T)
接口由通用集合对象使用,例如Dictionary(TKey,TValue)
,List(T)
,以及LinkedList(T)
,当使用包含
,IndexOf
,LastIndexOf
和删除
。
The
IEquatable(T)
interface is used by generic collection objects such asDictionary(TKey, TValue)
,List(T)
, andLinkedList(T)
when testing for equality in such methods asContains
,IndexOf
,LastIndexOf
, andRemove
.
IEquatable< T>
的实现将减少这些类的类型转换,因此会稍快一些而不是标准的 object.Equals
方法。例如,请查看两种方法的不同实现:
The IEquatable<T>
implementation will require one less cast for these classes and as a result will be slightly faster than the standard object.Equals
method that would be used otherwise. As an example see the different implementation of the two methods:
public bool Equals(T other)
{
if (other == null)
return false;
return (this.Id == other.Id);
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
T tObj = obj as T; // The extra cast
if (tObj == null)
return false;
else
return this.Id == tObj.Id;
}
这篇关于何时使用IEquatable< T>又为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!