它们真的一样吗?今天,我遇到了这个问题。这是立即窗口的转储:
?s
"Category"
?tvi.Header
"Category"
?s == tvi.Header
false
?s.Equals(tvi.Header)
true
?s == tvi.Header.ToString()
true
因此,s
和 tvi.Header
都包含“Category”,但是 ==
返回 false 并且 Equals()
返回真。
s
定义为字符串,tvi.Header
实际上是一个WPF TreeViewItem.Header
。那么,为什么他们返回不同的结果呢?我一直认为它们可以在 C# 中互换。
谁能解释这是为什么?
两个区别:
Equals
是多态的(即它可以被覆盖,所使用的实现将取决于目标对象的执行时类型),而 == 的实现
使用是根据对象的编译时类型确定的:
// 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
如果你在 null 上调用它会抛出异常,== 不会
string x = null;
string y = null;
if (x.Equals(y)) // NullReferenceException
if (x == y) // Yes
请注意,您可以使用 object.Equals
避免后者成为问题:
if (object.Equals(x, y)) // Fine even if x or y is null