string.Equals() 和 == 运算符真的一样吗? [英] Are string.Equals() and == operator really same?

查看:32
本文介绍了string.Equals() 和 == 运算符真的一样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

他们真的一样吗?今天,我遇到了这个问题.这是来自立即窗口的转储:

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 

所以,stvi.Header 都包含Category",但是 == 返回 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 是多态的(即它可以被覆盖,所使用的实现将取决于目标对象的执行时间类型),而 == 的实现 使用是根据对象的编译时类型确定的:

  • 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 如果你在 null 上调用它会抛出异常,== 不会

  • Equals will throw an exception if you call it on null, == won't

      string x = null;
      string y = null;
    
      if (x.Equals(y)) // NullReferenceException
    
      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屋!

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