平等双方之间的差值/ equals和==操作符? [英] Difference between Equals/equals and == operator?

查看:100
本文介绍了平等双方之间的差值/ equals和==操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 A == b a.Equals之间的差值(B)

推荐答案

假设类型的 A B 是引用类型:

Assuming the types of a and b are reference types:


  • 在Java中,==总是比较对的标识的 - 即两个值是否是同一个对象的引用。这也被称为的引用相等的。 Java没有任何用户定义的操作符重载。

  • In Java, == will always compare for identity - i.e. whether the two values are references to the same object. This is also called reference equality. Java doesn't have any user-defined operator overloading.

在C#这取决于。除非有一个操作符重载处理它,==会像Java的(即比较参考平等)。但是,如果有相匹配的过载的编译时间的类型 A B (例如,如果他们都声明为字符串),那么超载将被调用。这可以表现怎么想,但通常实现的值相等的(即 A B 可以参考,但不同的等于的价值观,它仍然会返回true)。

In C# it depends. Unless there's an overloaded operator which handles it, == will behave like Java (i.e. comparing for reference equality). However, if there's an overload which matches the compile-time types of a and b (e.g. if they're both declared as strings) then that overload will be called. That can behave how it wants, but it typically implements value equality (i.e. a and b can refer to different but equal values and it would still return true).

在两种语言中, a.Equals(B) a.equals(B)将调用虚拟等于 / 等于通过声明 Method对象,除非更具体超载已被的编译时类型介绍 A 。这可能会或可能不会在对象的执行时间类型覆盖的引用。在这两个.NET和Java中,对象执行还检查身份。请注意,这依赖于的执行时间型的而不是编译时类型的是重载依赖。

In both languages, a.Equals(b) or a.equals(b) will call the virtual Equals/equals method declared by Object, unless a more specific overload has been introduced by the compile-time type of a. This may or may not be overridden in the execution-time type of the object that a refers to. In both .NET and Java, the implementation in Object also checks for identity. Note that this depends on the execution-time type rather than the compilation-time type that overload resolution depends on.

当然,如果 A ,那么你会得到一个的NullReferenceException / NullPointerException异常当您尝试调用 a.equals(b) a.Equals(b)

Of course, if a is null then you'll get a NullReferenceException/NullPointerException when you try to call a.equals(b) or a.Equals(b).

这篇关于平等双方之间的差值/ equals和==操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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