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

代码如下:

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

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

你知道为什么会这样吗?


当前回答

I am a bit confused here. If the runtime type of Content is of type string, then both == and Equals should return true. However, since this does not appear to be the case, then runtime type of Content is not string and calling Equals on it is doing a referential equality and this explains why Equals("Energy Attack") fails. However, in the second case, the decision as to which overloaded == static operator should be called is made at compile time and this decision appears to be ==(string,string). this suggests to me that Content provides an implicit conversion to string.

其他回答

Equal和==之间的唯一区别是对象类型比较。在其他情况下,例如引用类型和值类型,它们几乎是相同的(要么都是位相等,要么都是引用相等)。

对象: Equals:位的相等 ==:引用相等

String:(equals和==对于String是相同的,但如果字符串中的一个被更改为object,则比较结果将不同) Equals:位的相等 ==:位相等

更多的解释请看这里。

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

Equals只是一个虚方法,因此将使用重写的版本(对于字符串类型比较内容)。

当比较对象引用和字符串时(即使对象引用引用了字符串),特定于字符串类的==操作符的特殊行为将被忽略。

Normally (when not dealing with strings, that is), Equals compares values, while == compares object references. If two objects you are comparing are referring to the same exact instance of an object, then both will return true, but if one has the same content and came from a different source (is a separate instance with the same data), only Equals will return true. However, as noted in the comments, string is a special case because it overrides the == operator so that when dealing purely with string references (and not object references), only the values are compared even if they are separate instances. The following code illustrates the subtle differences in behaviors:

string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;  // Notice: set to object variable!

Console.WriteLine($"{object.ReferenceEquals(s1, s2)} {s1 == s2} {s1.Equals(s2)}");
Console.WriteLine($"{object.ReferenceEquals(s1, s3)} {s1 == s3} {s1.Equals(s3)}");
Console.WriteLine($"{object.ReferenceEquals(s1, s4)} {s1 == s4} {s1.Equals(s4)}");

输出结果为:

True True True     // s1, s2
False True True    // s1, s3
False False True   // s1, s4

简介:

Variables .ReferenceEquals == .Equals
s1, s2 True True True
s1, s3 False True True
s1, s4 False False True

作为对已经很好的答案的补充:这种行为不仅限于字符串或比较不同的数字类型。即使两个元素的类型对象都是相同的基础类型。“==”不行。

下面的屏幕截图显示了比较两个object {int} -值的结果

给答案再加一分。

. equalsto()方法提供了比较区域性和区分大小写的方法。