写一个好的C#Equals方法 [英] Writing A Good C# Equals Method

查看:190
本文介绍了写一个好的C#Equals方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有任何人有一个模板写一个体面的equals方法 - 我记得在有效的Java有一圈处理问题与子类打交道时等于



我没有了本书我,我不记得,如果它很实用的建议 - 那么,你如何写一个坚实稳健的equals方法实施


解决方案

?可能是一个现成的墙,但建议:考虑在第一位不重写等于。基本上平等的性质不与子类好工作,因为你所提到的。但是,.NET API中几乎无处不在,它使用的平等(如字典,哈希集)允许的IEqualityComparer< T> 在传递制作不同的对象负责男女平等。 。让生活更加灵活:可以使用不同的对象来决定使用哪种标准



实施的IEqualityComparer< T> 要简单得多 - 你仍然需要检查无效,但你并不需要担心的类型是否合适,或是否等于将进一步覆盖<。 / p>

另一种方法,使正常的等于更顺利地进行是为了避免继承完全在大多数情况下 - 我可以'不记得在我的代码重写等于的允许派生类真的是有道理的最后一次。 密封 FTW:)


Does anyone have a template for writing a decent equals method - I remember in Effective Java there was problems around handling equals when dealing with subclasses.

I dont have the book with me and I cannot remember if it was practical advice - So how do you write a solid robust equals method implementation?

解决方案

Possibly an off-the-wall suggestion but: consider not overriding Equals in the first place. Basically the nature of equality doesn't work well with subclassing, as you mentioned. However, almost everywhere in the .NET API which uses equality (e.g. dictionaries, hash sets) allows an IEqualityComparer<T> to be passed in. Making a different object responsible for equality makes life much more flexible: you can use different objects to determine which criteria to use.

Implementing IEqualityComparer<T> is much simpler - you still need to check for nullity, but you don't need to worry about whether the types are appropriate, or whether Equals will be further overridden.

Another approach to making the normal Equals work more smoothly is to avoid inheritance entirely for the most part - I can't remember the last time it really made sense in my code to override Equals and allow derived classes. sealed FTW :)

这篇关于写一个好的C#Equals方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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