Entries

笔记:.NET中的相等比较操作符 / Note: The == operator in .NET

有一天碰上了诡异的问题,明明是相等的字符串,用==比较却总说不相等……
One day a strange problem issued, two strings with same content, but the == operator gave false...

然后问了别人一下,知道很多人都碰到过这种状况。
And confirmed this problem.

再然后一起研究知道了原来.NET框架它会特别关照字符串,还知道了运算符重载它是以怎么样个顺序来起作用的。
Lately we know that .NET Frameworks might take special care of strings, as well as how the operators work in order.

本来以为这样一切谜团就都解开了……
I thought that was all I should know...



但前几天突然想起来还有个Equals方法,去看了一下确认它是虚方法……
But days ago I realized there is a method called Equals, and I ensured it is virtual.

这就奇怪了,如果是虚方法的话,不就是说在不知道它具体是什么的时候就可以使用Equals方法了吗?那这样的话两个字符串应该相等才对吧?
Now it is interesting, as of being virtual, doesn't it mean overrided Equals could be called without realizing what that object is? Shouldn't the two strings being "same"?


于是我去试了一下,确认Equals的确认得出字符串,那么==它为什么会不认识呢……
So I tried it, and ensured an Equals call gives true, but the == operator...

这时只好求助于MSDN(好吧,学名叫MSDN资料库)了……
Now it's MSDN Library time...

嗯嗯,MSDN说了,要覆盖虚方法Equals,有必要先验证符号两边的东西是不是同一个对象,然后再来进一步比较……
Ummm, it says that, to override virtual method Equals, you should check are the two objects one first, then compare them further...

就是说,要强制转换成Object然后用==比较,或者用ReferenceEquals进行比较……
That means, convert to "Object" and use the == operator, or use ReferenceEquals instead...

也就是说,Equals似乎离不开Object的==……
Therefore, the method Equals can't stand without the == operator of "Object"...

也就是说,如果Object的==调用Equals,就死循环了……
Therefore, if the == operator of "Object" uses Equals, we get an endless loop...

于是谜团解开了,==和Equals虽然很像,但Object的==其实是不会跟Equals有什么往来的。=v=
So it is now clear, though == and Equals are similar, but the == operator of "Object" won't call Equals.


可是万一左边是null的话就麻烦了……="=a
But we got problem now if the left one is null...

为了不让.NET它大惊小怪,咱们可以先检查一下左边是不是null。
To avoid an exception, we could check if the left one is null first.

不过如果用静态方法Object.Equals的话就不用这么麻烦了。=v=
And if static method Object.Equals is used, you get easy life.

至于是a == b还是a.Equals(b)还是Object.Equals(a, b)嘛……
Finally, feel free to choose from "a == b", "a.Equals(b) and "Object.Equals(a, b)"...
引用此文章(FC2博客用户)
http://shinron4.blog126.fc2blog.us/tb.php/33-a9d8f473

引用

留言

发表留言

发表留言
只对管理员显示

Appendix

自我介绍

优雅的神棍 / Elegant Tales

Author:优雅的神棍 / Elegant Tales
神棍你好,神棍再见。

最新引用

QR

QR

羔羊们啊

加为好友

和此人成爲好友

搜寻栏