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

代码如下:

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

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

你知道为什么会这样吗?


当前回答

当我们创建任何对象时,对象有两个部分,一个是内容,另一个是对该内容的引用。 ==比较内容和引用; Equals()只比较内容

http://www.codeproject.com/Articles/584128/What-is-the-difference-between-equalsequals-and-Eq

其他回答

当我们创建任何对象时,对象有两个部分,一个是内容,另一个是对该内容的引用。 ==比较内容和引用; Equals()只比较内容

http://www.codeproject.com/Articles/584128/What-is-the-difference-between-equalsequals-and-Eq

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

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

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

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

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.

注意,在c#中有两种不同类型的等式

1-值相等(对于int, DateTime和struct等值类型)

2-引用平等(对象)

有两个基本的标准协议来实现相等性检查。

1- ==和!=运算符。

2- virtual Equals方法。

==和!=是静态解析的,这意味着c#将在编译时决定哪种类型将执行比较。

例如值类型

 int x = 50;
 int y = 50;
 Console.WriteLine (x == y); // True

但是对于参考类型

 object x = 50;
 object y = 50;
 Console.WriteLine (x == y); // False 

Equals()最初在运行时根据操作数的实际类型解析。

例如,在下面的例子中,在运行时,将决定Equals()将应用于int值,结果为真。

object x = 5;
object y = 5;
Console.WriteLine (x.Equals (y)); // True

但是,对于引用类型,它将使用引用相等性检查。

MyObject x = new MyObject();
MyObject y = x;
Console.WriteLine (x.Equals (y)); // True

注意Equals()对struct使用结构比较,这意味着它对struct的每个字段调用Equals。