是重要的重载equals如果我实现IEquatable< T&GT ;? [英] Is it important to override Equals if I'm implementing IEquatable<T>?

查看:142
本文介绍了是重要的重载equals如果我实现IEquatable< T&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道压倒一切的重要性的GetHashCode 实现自定义平等检查​​时 - 对此,我已实施 IEquality< T> 接口,并且还的区别普通和非普通的等于这里讨论。现在是有一个点覆盖等于(对象T)?会不会一切都在通用来到等于(T T)



 公共覆盖INT的GetHashCode()//用于hashsets和词典
{
返回标识要求;
}

公共布尔等于(T等)// IEquatable< T>这里
{
返回标识== other.Id;
}

公众覆盖布尔等于(obj对象)//要求?
{
返回等于(OBJ为T);
}


解决方案

从的 MSDN




如果您实现IEquatable,你也应该覆盖的Object.Equals(对象)和GetHashCode的基础
类的实现,使
他们的行为与该IEquatable.Equals $ b $一致b法。如果你这样做重写的Object.Equals(对象),你重写
实施也被称为中调用静态
等于(System.Object的,System.Object的)方法在你的类。在
此外,你应该重载op_Equality和op_Inequality
运营商。这将确保平等所有测试返回一致的
的结果。




我可以做一个更好的谷歌搜索了。这里有一个的好MSDN上的博客由JaredPar文章的主体。



在短,覆盖等于(obj对象)




所需静态的等于(对象OBJ1,对象OBJ2)上的 的方法对象的类,或包含(对象项目)的上的的ArrayList 的实例等。




接受这个,因为链接更彻底的的主题。由于俄德太..


I know the importance of overriding GetHashCode when implementing custom equality checks - for which I have implemented IEquality<T> interface, and also the difference between generic and non-generic Equals as discussed here. Now is there a point to override Equals(object t)? Wouldn't everything come under generic Equals(T t)?

public override int GetHashCode() //required for hashsets and dictionaries
{
    return Id;
}

public bool Equals(T other) //IEquatable<T> here
{
    return Id == other.Id;
}

public override bool Equals(object obj) //required??
{
    return Equals(obj as T);
}

解决方案

From msdn:

If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results.

I could have done a better google search too. Here's a good article on msdn blogs by JaredPar on the subject.

In short, overriding Equals(object obj):

Needed for the static Equals(object obj1, object obj2) method on object class, or for Contains(object item) on ArrayList instance etc..

Accepting this since the link is more thorough on the subject. Thanks to Oded too..

这篇关于是重要的重载equals如果我实现IEquatable&LT; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆