在装箱布尔类型上使用 == 运算符和 Equals 方法有什么区别?
鉴于这两个语句...
((object)false) == ((object)false)
((object)false).Equals((object)false)
第一个语句返回 false。 第二条语句返回 true。
我明白为什么第一个语句返回 false - 当布尔值被装箱时,它变成引用类型,并且两个引用不相等。但是,为什么/如何第二个语句结果为 true?
Given these two statements...
((object)false) == ((object)false)
((object)false).Equals((object)false)
The first statement returns false.
The second statement returns true.
I understand why the first statement returns false - when the boolean is boxed, it becomes a reference type, and the two references are not equal. But, why / how does the second statement result in true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为基本上它仍然在调用多态
Equals
方法。使用不同类型演示的示例代码:
仍然打印“Foo.Equals called!”因为在“盒子”上调用 Equals 方法仍然会调用
Foo.Equals
。现在
==
不是被覆盖,而是重载...所以如果你写:那将总是比较用于参考身份,而无需运行任何特定于类型的代码。
Because it's still calling the polymorphic
Equals
method, basically.Sample code to demonstrates with a different type:
That still prints "Foo.Equals called!" because calling the Equals method on the "box" still calls
Foo.Equals
.Now
==
isn't overridden, it's overloaded... so if you write:That will always compare for reference identity, without ever running any type-specific code.
这篇文章也许能够回答您的问题:
http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should -i-use-equals.aspx
This article may be able to answer your question:
http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx
正如您所说,第一个示例检查引用是否相等,而第二个示例检查每个对象的值是否相等。
来自 MSDN:
Just as you said, the first example checks whether the references are equal, while the second checks for equal values for each object.
From MSDN:
运算符重载不是多态的,但 Equals 是多态的。尽管
bool
有一个重载的 ==,通过将其转换为object
,您正在使用object
的实现,它会比较引用相等性。但您仍在使用Equals
的bool
版本。Operator overloading is not polymorphic but
Equals
is. Even thoughbool
has an overloaded ==, by casting it toobject
you're usingobject
's implementation, which compares reference equality. But you're still using thebool
version ofEquals
.Equals
方法是一个虚拟方法,被Boolean
类型覆盖。因此,在第二行中将bool
转换为object
并不重要;它仍然使用类型的 vtable 来查找对象的实际类型提供的Equals
实现(这就是多态性!)。==
运算符是一个静态运算符,因此在编译时会选择适当的重载。编译器看到您将object
类型的两个对象与该运算符进行比较,因此它选择(object, object)
重载。这是一个愚蠢的小程序来说明差异:
The
Equals
method is a virtual method which is overridden by theBoolean
type. So it doesn't matter that you're casting thebool
to anobject
in the second line; it's still using the type's vtable to look up the implementation ofEquals
provided by the object's actual type (that's polymorphism for you!).The
==
operator is a static operator and so the appropriate overload is selected at compile time. The compiler sees you comparing two objects of typeobject
with that operator and so it selects the(object, object)
overload.Here's a stupid little program to illustrate the difference:
第一个是参考,第二个是价值观!
1st one is for references, second one is for values!