給然後按照類聲明:無法執行重載方法
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(員工),但出於某種原因,它不工作:
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),但後者被調用。我究竟做錯了什麼?
更新的響應。 Equals的當前實施可能沒有達到你的希望。 – 2012-07-10 16:48:09