为什么Object.Equals更喜欢从实例调用String.Equals?

Apc*_*ite 1 c# string equality

我准备在C#上进行认证,并面对以下问题(为简单起见编辑代码):

class Class
{
    public string Name { get; set; } = "hello";
}

...

Class a = new Class();
Class b = new Class();
Class c = a;

Assert.IsTrue(a.Name == b.Name);
Assert.IsTrue(a.Name.Equals(b.Name));
Assert.IsTrue(Object.Equals(a.Name, b.Name));

Assert.IsTrue(a.Name == c.Name);
Assert.IsTrue(a.Name.Equals(c.Name));
Assert.IsTrue(Object.Equals(a.Name, c.Name));

Assert.IsTrue(a.Name == a.Name);
Assert.IsTrue(a.Name.Equals(a.Name));
Assert.IsTrue(Object.Equals(a.Name, a.Name));
Run Code Online (Sandbox Code Playgroud)

所有这些断言都过去了.

认证测试的转储表明这Object.Equals(*.Name, *.Name)是正确的答案并且*.Name.Equals(*.Name)是错误的.

为什么?

Ole*_*kov 7

因为如果是while x.Name.Equals(y.Name)将抛出将执行有效的比较NullReferenceExceptionx.NamenullObject.Equals(x.Name, y.Name)