如果(< object> ==< int>) [英] if (<object> == <int>)
问题描述
我不明白,为什么下图中的if
语句返回false.
我希望你能向我解释.
I can't understand, why the if
statement in the picture below returns false.
I hope you can explain it to me.
您会看到,两个变量的值和类型都相同.
You can see, that the values and the typs of both variables are the same.
推荐答案
您正在调用的==
运算符是带有两个object
参数的重载.这使用引用相等-值并不重要,它必须是相同的对象.
The ==
operator you are calling is the overload that takes two object
parameters. This uses reference equality - the value isn't important, it has to be the same object.
您可以在文档中阅读:
对于字符串以外的引用类型,== 如果其两个操作数引用相同的对象,则返回true .对于字符串类型,==比较字符串的值.
For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.
虽然int
是值类型,但已被装箱" (包装在object
中).您正在比较两种包装整数的引用类型.
While int
is a value type, it has been 'boxed' (wrapped in an object
). You are comparing the two different reference types that wrap your integers.
要解决此问题,可以改用object.Equals
-这将比较两个整数.
To fix this, you can use object.Equals
instead - this will compare the two integers.
item.Equals(value);
或静态方法(可以处理item == null
的情况):
Or the static method (which would handle the case where item == null
):
object.Equals(item, value);
如果您取消对int
的装箱,则可以按预期使用==
的int
重载:
If you unbox to int
then you can use the int
overload of ==
as you expect:
(int)item == (int)value;
同样,根据文档:
对于预定义的值类型,等于运算符(==)如果其操作数的值相等,则返回true.
这篇关于如果(< object> ==< int>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!