本文介绍了何时使用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.
我缺少什么?
推荐答案
从:
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>又为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!