是string.Equals()和==操作符真的一样吗? [英] Are string.Equals() and == operator really same?
问题描述
他们是真的一样吗?今天,我遇到了这个问题。这里是从即时窗口转储:
Are they really same? Today, I ran into this problem. Here is the dump from the Immediate Window:
?s
"Category"
?tvi.Header
"Category"
?s == tvi.Header
false
?s.Equals(tvi.Header)
true
?s == tvi.Header.ToString()
true
那么,s和tvi.Header包含类别,但是==返回false和equals返回true。
So, both s and tvi.Header contain "Category", but == returns false and Equals returns true.
s被定义为字符串,tvi.Header实际上是一个WPF TreeViewItem.Header。那么,为什么他们返回不同的结果?我一直以为他们是在C#中互换。
s is defined as string, tvi.Header is actually a WPF TreeViewItem.Header. So, why are they returning different results? I always thought that they were interchangable in C#.
任何人能解释这是为什么?
Can anybody explain why this is?
推荐答案
两处不同:
-
等于
是多态(即它可以被覆盖,并且所使用的实现将依赖于目标对象的执行时间型),而实施的==
采用的是基于确定的编译时间的类型的对象:
Equals
is polymorphic (i.e. it can be overridden, and the implementation used will depend on the execution-time type of the target object), whereas the implementation of==
used is determined based on the compile-time types of the objects:
// Avoid getting confused by interning
object x = new StringBuilder("hello").ToString();
object y = new StringBuilder("hello").ToString();
if (x.Equals(y)) // Yes
// The compiler doesn't know to call ==(string, string) so it generates
// a reference comparision instead
if (x == y) // No
string xs = (string) x;
string ys = (string) y;
// Now *this* will call ==(string, string), comparing values appropriately
if (xs == ys) // Yes
等于
如果你调用它空会去的一声,==不会
Equals
will go bang if you call it on null, == won't
string x = null;
string y = null;
if (x.Equals(y)) // Bang
if (x == y) // Yes
请注意,您可以避开后者是使用问题的Object.Equals
:
Note that you can avoid the latter being a problem using object.Equals
:
if (object.Equals(x, y)) // Fine even if x or y is null
这篇关于是string.Equals()和==操作符真的一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!