==和equals的C#差() [英] C# difference between == and Equals()
问题描述
我有,当我使用的比较两个字符串,出于某种原因,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$c$c>.
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屋!