无法执行重载方法

时间:2012-07-10 07:02:15

标签: c#-4.0 override overloading

然后给出以下类声明:

   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)的签名更匹配,但后者被调用。我做错了什么?

2 个答案:

答案 0 :(得分: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");
}

<强>更新

如果您的意图是覆盖Object.Equals(object o),则您的Equals方法的签名不正确。您的方法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

答案 1 :(得分:0)

从此更改条件 if (a.Equals(b as Employee))

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