问题描述
让我们说我们有两个对象o1&在我的情景o1&中定义为System.Object的o2.o2可以是以下任何一种类型:
Lets say we have two objects o1 & o2 defined as System.Object, in my situtaion o1 & o2 can be any of the following types:
- 字符串
- Int32
- Double
- 布尔值
- DateTime
- DBNull
那么我该如何检查o1&o2相等,因此是相同的对象,或者都具有相同的类型&值.
So how can I check that o1 & o2 are equal, therefore are the same object or both have the same type & value.
我可以只做 o1 == o2
还是要做 o1.Equals(o2)
或其他事情?
Can I just do o1 == o2
or do I need to do o1.Equals(o2)
or something else?
谢谢
AJ
推荐答案
我建议您使用
object.Equals(o1, o2)
因为那样也可以解决无效性.(假设您希望两个空引用进行相等比较.)
as that will cope with nullity as well. (That assumes you want two null references to compare as equal.)
您不应不使用 ==
,因为运算符不是多态应用的;类型 overload ==,但它们不会 override (没有要覆盖的内容).如果您使用
You should not use ==
because operators are not applied polymorphically; the types overload == but they don't override it (there's nothing to override). If you use
o1 == o2
,它将比较它们的引用身份,因为变量被声明为 object
类型.
that will compare them for reference identity, because the variables are declared to be of type object
.
在 o1
为null的情况下,使用 o1.Equals(o2)
可以正常工作 -届时它将抛出 NullReferenceException
.
Using o1.Equals(o2)
will work except in the case where o1
is null - at which point it would throw a NullReferenceException
.
这篇关于.net对象相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!