c# - string.Equals() 和 == 运算符真的一样吗?

标签 c# string

<分区>

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

?s 
"Category" 
?tvi.Header 
"Category" 
?s == tvi.Header 
false 
?s.Equals(tvi.Header) 
true 
?s == tvi.Header.ToString() 
true 

因此,stvi.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

关于c# - string.Equals() 和 == 运算符真的一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3678792/

相关文章:

使用 ppPasteMetafilePicture 时,C# vsto Powerpoint PasteSpecial 失败

c# - 当我刷新我的 gridview 时如何到达 page1?

c# - 如何在 Aspose.PDF .NET 中旋转表格单元格中的文本

java - 最有效的方法来实现这个?

java - 存储字符串数组唯一列表的最佳方式

swift - 将 URL 转换为 AVAsset - Swift

javascript - 有没有办法可以使用 CKEditor 随时随地修改 MS Word 文档并将其保存在我的服务器中的某个位置

c# - 将 JObject 添加到 JObject

java - 文本字段中没有显示任何内容

正则表达式删除R中的前导零,除非最终(或唯一)字符为零