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

代码如下:

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

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

你知道为什么会这样吗?


当前回答

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

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

其他回答

The == token in C# is used for two different equality-check operators. When the compiler encounters that token, it will check whether either of the types being compared has implemented an equality-operator overload for either the specific combination types being compared(*), or for a combination of types to which both types can be converted. If the compiler finds such an overload it will use it. Otherwise, if the two types are both reference types and they are not unrelated classes (either may be an interface, or they may be related classes), the compiler will regard == as a reference-comparison operator. If neither condition applies, compilation will fail.

请注意,其他一些语言为两个相等检查操作符使用单独的令牌。在VB。例如,=令牌在表达式中仅用于可重载的相等检查操作符,而is则用作引用测试或空测试操作符。在没有覆盖相等检查操作符的类型上使用=将会失败,在测试引用是否相等或为空之外的任何目的上尝试使用Is也会失败。

(*)Types generally only overload equality for comparison with themselves, but it may be useful for types to overload the equality operator for comparison with other particular types; for example, int could have (and IMHO should have but didn't) defined an equality operators for comparison with float, so that 16777217 would not report itself equal to 16777216f. As it is, since no such operator is defined, C# will promote the int to float, rounding it to 16777216f before the equality-check operator sees it; that operator then sees two equal floating-point numbers and reports them as equal, unaware of the rounding that took place.

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

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

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

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

因为到目前为止还没有提到. 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。

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

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