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

代码如下:

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

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

你知道为什么会这样吗?


当前回答

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

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

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

更多的解释请看这里。

其他回答

当==用于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.

Equals()和==是否相同取决于实现。因为c#允许用户分别为Equals()和==设置不同的行为。

    class CompareTest
    {
        public readonly int val;

        public CompareTest(int val)
        {
            this.val = val;
        }

        public override bool Equals(object obj)
        {
            return obj is CompareTest test && this.val == test.val;
        }

        public override int GetHashCode()
        {
            return val;
        }

        public static bool operator == (CompareTest a, object b)
        {
            return Equals(a, b);
        }

        public static bool operator != (CompareTest a, object b)
        {
            return !(a == b);
        }
    }

在本例中,我使Equals()和==具有相同的行为。但如果我让他们不一样呢?例如:

        public static bool operator == (CompareTest a, object b)
        {
            return false;
        }

Equals()正常工作,但==永远不会工作。

此外,虽然我让它们具有相同的行为,但仍然有一个区别:哪个==函数将被调用取决于左边的值:

        Compare Test a = new CompareTest(1);
        object b = new CompareTest(1);
        CompareTest c = new CompareTest(1);
        Debug.Log("AB " + (a == b)); // true
        Debug.Log("BA " + (b == a)); // false! because it calls object's == function 
        Debug.Log("AC " + (a == c)); // true
        Debug.Log("CA " + (c == a)); // true

给答案再加一分。

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

非常棒的答案和例子!

我想补充一下两者之间的根本区别,

像==这样的操作符不是多态的,而Equals是

记住这个概念,如果你算出任何例子(通过查看左手和右手引用类型,并检查/知道类型是否确实重载了==操作符和重写了Equals),你肯定会得到正确的答案。