重载运算符==对的equals() [英] Overloading operator== versus Equals()

查看:156
本文介绍了重载运算符==对的equals()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#项目合作上,到现在为止,我已经使用不可变对象和工厂,以确保类型的对象可总是被比较与平等==

I'm working on a C# project on which, until now, I've used immutable objects and factories to ensure that objects of type Foo can always be compared for equality with ==.

对象不能改变一旦创建,工厂始终返回一组给定的参数相同的对象。这个伟大的工程,并在整个code碱基我们假设 == 总是适用于检查平等的。

Foo objects can't be changed once created, and the factory always returns the same object for a given set of arguments. This works great, and throughout the code base we assume that == always works for checking equality.

现在我需要增加一些功能,引入了一个边缘的情况下,此将不总是有效。做最简单的事情是重载运算符== 为该类型,所以没有其他的code的项目需要改变。但是,这让我觉得作为一个code气味:超载运算符== ,而不是等于只是似乎不可思议,和我习惯了 == 检查引用相等,且约定等于检查对象相等(或任何术语是)。

Now I need to add some functionality that introduces an edge case for which this won't always work. The easiest thing to do is to overload operator == for that type, so that none of the other code in the project needs to change. But this strikes me as a code smell: overloading operator == and not Equals just seems weird, and I'm used to the convention that == checks reference equality, and Equals checks object equality (or whatever the term is).

这是一个合理的担忧,或者我应该继续前进,过载运算符==

Is this a legitimate concern, or should I just go ahead and overload operator ==?

推荐答案

我认为标准是,对于大多数类型,.Equals检查对象的相似性,和运营商 == 检查引用相等。

I believe the standard is that for most types, .Equals checks object similarity, and operator == checks reference equality.

我认为最好的做法是,对不可变类型,运营商 == 应检查相似性,以及 .Equals 。如果你想知道,如果他们真的是同一个对象,使用 .ReferenceEquals 。看到C#字符串类的这样的一个例子。

I believe best practice is that for immutable types, operator == should be checking for similarity, as well as .Equals. And if you want to know if they really are the same object, use .ReferenceEquals. See the C# String class for an example of this.

这篇关于重载运算符==对的equals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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