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

代码如下:

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

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

你知道为什么会这样吗?


当前回答

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

> 2 == 2.0
True

> 2.Equals(2.0)
False

对于字符串

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

> x.Equals(null)
NullReferenceException

在这两种情况下,==比.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是

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

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

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

==

==运算符可用于比较任何类型的两个变量,它只是比较比特。

int a = 3;
byte b = 3;
if (a == b) { // true }

注意:在int的左边有更多的0,但我们在这里不关心它。

Int a(00000011) ==字节b (00000011)

记住==运算符只关心变量中比特的模式。

如果两个引用(原语)指向堆上的同一个对象,则使用==。

无论变量是引用还是原语,规则都是相同的。

Foo a = new Foo();
Foo b = new Foo();
Foo c = a;

if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }

A == c是正确的 A == b是假的

a和c的位模式是相同的,所以使用==它们是相等的。

等于():

使用equals()方法查看两个不同的对象是否相等。

例如两个不同的String对象都表示“Jane”中的字符

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

> 2 == 2.0
True

> 2.Equals(2.0)
False

对于字符串

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

> x.Equals(null)
NullReferenceException

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