2012-07-10 73 views
0

給然後按照類聲明:無法執行重載方法

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),但後者被調用。我究竟做錯了什麼?

回答

2

private static void CompareObjects(Object a, Object b) 

您使用

a.Equals 

然而a是Object類型的,讓你在使用的Object.Equals()。 您正在調用a的Equals()方法,而不是b

如果你希望兩個ab爲類型Employee你可以寫

if (((Employee)a).Equals(b)) Console.WriteLine("a.Equals(b) returns true"); 

if ((a as Employee).Equals(b)) Console.WriteLine("a.Equals(b) returns true"); 

然而,無論是變種會拋出的a一個例外是Employee類型沒有。

相反,考慮

Employee aEmployee = a as Employee; 
if (aEmployee != null) 
{ 
    if (aEmployee.Equals(b)) Console.WriteLine("a.Equals(b) returns true"); 
} 

UPDATE

您的Equals的簽名,如果你的目的是覆蓋Object.Equals(object o)方法是不正確的。您的方法Employee.Equals(Employee e)仍不會被書寫。如果你想覆蓋Object.Equals(object o),並且如果你希望非員工的東西永遠不等於員工的東西,我會推薦以下模式。

public override bool Equals(object obj) 
{ 
    // If the references are equal, objects must be equal 
    if (object.ReferenceEquals(this, obj)) return true; 

    Employee other = obj as Employee; 

    // obj is not able to be cast to Employee, no need to compare further 
    if (other == null) return false; 

    // Here, implement the checks you need to compare two 
    // Employee instances for equality 
    return this.FirstName == other.FirstName /* && etc. */; 
} 

請注意,只要你重寫的Equals()語義,你幾乎可以肯定要覆蓋GetHashCode()爲好。見

Simplify Overriding Equals(), GetHashCode() in C# for Better Maintainability

+0

更新的響應。 Equals的當前實施可能沒有達到你的希望。 – 2012-07-10 16:48:09

0

變化從這個 if (a.Equals(b as Employee))
的條件

if ((Employee)a.Equals(b as Employee))