== 和 Equals() 之间的 C# 区别 [英] C# difference between == and Equals()

查看:30
本文介绍了== 和 Equals() 之间的 C# 区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Silverlight 应用程序中有一个条件比较 2 个字符串,出于某种原因,当我使用 == 时它返回 false.Equals() 返回 true.

I have a condition in a silverlight application that compares 2 strings, for some reason when I use == it returns false while .Equals() returns true.

代码如下:

if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack"))
{
    // Execute code
}

if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")
{
    // Execute code
}

有什么原因可以解释为什么会这样吗?

Any reason as to why this is happening?

推荐答案

== 用于 object 类型的表达式时,它会解析为 System.Object.ReferenceEquals.

When == is used on an expression of type object, it'll resolve to System.Object.ReferenceEquals.

Equals 只是一个 virtual 方法和行为如此,因此将使用覆盖的版本(对于 string 类型比较内容).

Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).

这篇关于== 和 Equals() 之间的 C# 区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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