我遇到了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#中失败了吗?我的哪些假设是错误的?
object.operator==
使用object.ReferenceEquals
,但string.operator==
使用object.Equals
。这对我来说很反直觉,因为object.Equals
是虚拟的,所以它已经可以在object.operator==
中使用了。 - wigy