我在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方法的静态版本,所以我想在这里添加它来总结和比较这3种变体。

MyString.Equals("Somestring"))          //Method 1
MyString == "Somestring"                //Method 2
String.Equals("Somestring", MyString);  //Method 3 (static String.Equals method) - better

其中MyString是一个变量,它来自代码中的其他地方。

背景信息和总结:

在Java中,不应该使用==来比较字符串。我提到这一点是为了防止你需要使用两种语言 让你知道在c#中使用==也可以用更好的东西代替。

在c#中,使用方法1或方法2比较字符串没有实际区别,只要两者都是字符串类型。但是,如果一个为空,一个为其他类型(如整数),或者一个表示具有不同引用的对象,那么,正如最初的问题所示,您可能会遇到比较相等的内容可能不会返回您所期望的结果。

建议解决方案:

因为在比较时使用==与使用. equals不完全相同,所以可以使用静态String。改为= method。这样,如果两边不是相同的类型,您仍然可以比较内容,如果其中一方为空,则可以避免异常。

   bool areEqual = String.Equals("Somestring", MyString);  

写起来有点麻烦,但在我看来,使用起来更安全。

以下是从微软复制的一些信息:

public static bool Equals (string a, string b);

参数

一个字符串

要比较的第一个字符串,或null。

b字符串

要比较的第二个字符串,或null。

返回布尔值

如果a的值与b的值相同,则为真;否则,假的。如果a和b都为空,则该方法返回true。

其他回答

首先,两者有区别。对数字的

> 2 == 2.0
True

> 2.Equals(2.0)
False

对于字符串

> string x = null;
> x == null
True

> x.Equals(null)
NullReferenceException

在这两种情况下,==比.Equals更有用

注意,在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。

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

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

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