C#==运算符详细说明了什么? [英] C# what does the == operator do in detail?

查看:166
本文介绍了C#==运算符详细说明了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#中,当你在两个对象上与==运算符进行比较时,后台究竟会发生什么?它只是比较地址?或者像Equals()或CompareTo()那样?

in c# what does exactly happen in the background when you do a comparison with the "==" operator on two objects? does it just compare the addresses? or does it something like Equals() or CompareTo() ?

PS:java中的==运算符怎么样?它的行为是否相同?

PS: what about the "==" operator in java? does it behave the same?

推荐答案

据我所知:


  • 它按值(相等)比较值类型

  • 它按引用比较引用类型(标识)

  • 除外如果==运算符重载,则调用该运算符。

Equals在object中实现,也可以重写。 Object中的默认实现执行引用类型的引用比较。所以默认情况下,Equals和==都是一样的。

Equals is implemented in object and can be overridden as well. The default implementation in Object performs a reference comparison for reference types. So by default, Equals and == do the same.

我认为在java中你不能重载==运算符。但是我的Java知识已经过时了。

I think in java you cannot overload the == operator. But my Java knowledge is pretty outdated.

编辑:
请注意 == operator是一个静态方法。它在编译时绑定,基于变量或字段的类型。 Equals 是一个在运行时根据实际运行时类型找到的虚方法。

Note that the == operator is a static method. It is bound at compile time, base on the types of your variables or fields. Equals is a virtual method that is found at runtime, based on actual runtime types.

这篇关于C#==运算符详细说明了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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