==和equals的C#差() [英] C# difference between == and Equals()

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

问题描述

我有,当我使用的比较两个字符串,出于某种原因,Silverlight应用程序的条件 == 返回,而 .Equals()收益真正

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.

下面是code:

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?

推荐答案

== 是在类型的前pression使用对象,它会解析到<一个href=\"https://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx\"><$c$c>System.Object.ReferenceEquals.

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

等于 仅仅是一个虚拟方法和行为正因为如此,所以重写版本将使用(对于字符串类型的内容进行比较)

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天全站免登陆