From the MSDN:
The IEquatable(T)
interface is used by generic collection objects such as Dictionary(TKey, TValue)
, List(T)
, and LinkedList(T)
when testing for equality in such methods as Contains
, IndexOf
, LastIndexOf
, and Remove
.
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…