==或.Equals() [英] == or .Equals()

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

问题描述

为什么要使用一个比其他?

Why use one over the other?

推荐答案

==是身份的考验。如果被测试的两个对象其实都是同一个对象,它将返回true。 等于()执行相等测试,如果两个对象认为自己等于将返回true。

== is the identity test. It will return true if the two objects being tested are in fact the same object. Equals() performs an equality test, and will return true if the two objects consider themselves equal.

身份测试速度更快,所以当没有必要对更昂贵的平等的测试,你可以使用它。例如,比较反对或空字符串。

Identity testing is faster, so you can use it when there's no need for more expensive equality tests. For example, comparing against null or the empty string.

这是可能超载其中任一提供不同的行为 - 对象身份鉴定的equals() - ,但对任何人的缘故读你的code,请不要。

It's possible to overload either of these to provide different behavior -- like identity testing for Equals() --, but for the sake of anybody reading your code, please don't.

指出了如下:某些类型的像字符串的DateTime 提供过载 = = 运算符给它平等的语义。因此,确切的行为将取决于类型你是比较对象。

Pointed out below: some types like String or DateTime provide overloads for the == operator that give it equality semantics. So the exact behavior will depend on the types of the objects you are comparing.

另请参阅:

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

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