2012-07-10 70 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))