然后给出以下类声明:
class Employee {
public string Name { get; set; }
public int Age { get; set; }
public override bool Equals(object obj)
{
Console.WriteLine("In Equals(Object)");
if (obj is Employee)
if (this.Name == (obj as Employee).Name && this.Age == (obj as Employee).Age)
return true;
else
return false;
else
return false;
}
public bool Equals(Employee obj)
{
Console.WriteLine("In Equals(Employee)");
return this.Equals(obj as Object);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
我正在尝试使用 Employee.Equals(Employee) 但由于某种原因它不起作用:
private static void CompareObjects(Object a, Object b)
{
if (a.Equals(b as Employee)) Console.WriteLine("a.Equals(b) returns true");
else Console.WriteLine("a.Equals(b) returns false");
}
当我将 b 转换为 Employee 时,我期望 Employee.Equals(Employee) 会被调用,因为它比 Employee.Equals(Object) 更好地匹配签名,但后者被调用了。我究竟做错了什么?