在下面的示例中,第三个评估返回 false,一切都很好,但第四个示例返回 true。
但是,我不太明白这是如何工作的,默认情况下Object.Equals
比较对象相等的两个引用,并且看到 asa
和b
都指向一个唯一的一个字符串的实例,这应该返回 false,它在第三个示例中执行此操作,但在第四个示例中没有。
现在我明白了为什么它在第二个示例中返回 true,因为该.Equals()
方法在字符串类中被覆盖,但在第四个示例中,我们将此字符串转换为对象。那么在这种情况下
它不会调用吗?Object.Equals
static void Main()
{
// Create two equal but distinct strings
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
Console.WriteLine (a == b); // Returns true
Console.WriteLine (a.Equals(b)); // Returns true
// Now let's see what happens with the same tests but
// with variables of type object
object c = a;
object d = b;
Console.WriteLine (c == d); // Returns false
Console.WriteLine (c.Equals(d)); // Returns true
}