Object.Equals是虚拟的,但Object.operator==在C#中不使用它?
我在 C# 中遇到了一个我不太理解的奇怪的“不对称性”。请参阅以下代码:
using System;
using System.Diagnostics;
namespace EqualsExperiment
{
class Program
{
static void Main(string[] args)
{
object apple = "apple";
object orange = string.Format("{0}{1}", "ap", "ple");
Console.WriteLine("1");
Debug.Assert(apple.Equals(orange));
Console.WriteLine("2");
Debug.Assert(apple == orange);
Console.WriteLine("3");
}
}
}
对于所有 .NET 专家来说,这可能是显而易见的,但第二个断言失败了。
在Java中,我了解到==是这里所谓的Object.ReferenceEquals的同义词。在C#中,我认为Object.operator==使用Object.Equals,它是虚拟的,所以它在System.String类中被重写。
有人可以解释一下,为什么 C# 中的第二个断言失败?我的哪些假设是错误的?
I got hit by a strange "asymmetry" in C# that I do not really understand. See the following code:
using System;
using System.Diagnostics;
namespace EqualsExperiment
{
class Program
{
static void Main(string[] args)
{
object apple = "apple";
object orange = string.Format("{0}{1}", "ap", "ple");
Console.WriteLine("1");
Debug.Assert(apple.Equals(orange));
Console.WriteLine("2");
Debug.Assert(apple == orange);
Console.WriteLine("3");
}
}
}
It might be obvious for all you .NET gurus, but the 2nd assert fails.
In Java I have learnt that == is a synonym for something called Object.ReferenceEquals here. In C#, I thought that Object.operator== uses Object.Equals, which is virtual, so it is overriden in the System.String class.
Can someone explain, why does the 2nd assert fail in C#? Which of my assumptions are bad?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
运算符被定义为静态方法,因此它们不能参与多态性。因此,您的第二个断言使用
object
的==
定义(因为您的变量被声明为object
),这仅测试引用相等性。如果变量被声明为string
,则将使用string
的==
重载,并且第二个断言将会成功。Operators are defined as static methods, so they can't participate in polymorphism. So your second assert uses the definition of
==
forobject
(since your variables are declared asobject
), which only tests reference equality. If the variables were declared asstring
, the==
overload forstring
would have been used, and the second assert would have succeeded.==
运算符不是同义词,它是为不同类型定义的运算符。==
运算符是为字符串定义的,然后它实际上使用Equals
方法:但是,在您的代码中,您没有在字符串上使用运算符,而是使用它作用于对象,因此您得到的是为对象定义的
==
运算符,它使用ReferenceEquals
进行比较。使用哪种运算符重载是在编译时决定的,因此决定重载的是变量的类型,而不是变量指向的对象的实际类型。
The
==
operator is not a synonym, it's an operator that is defined for different types.The
==
operator is defined for strings, and then it does actually use theEquals
method:However, in your code you are not using the operator on strings, you are using it on objects, so what you get is the
==
operator defined for objects, which usesReferenceEquals
to do the comparison.Which overload of the operator to use is decided at compile time, so it's the type of the variables that decide the overload, not the actual type of the objects that the variables point to.