在子类中正确实现Equals和GetHashCode

时间:2016-03-17 18:34:59

标签: c# equals

我们假设我有以下抽象类学生:

public abstract class Student
{
    public string studentID {get; private set;}
    public string FirstName {get; private set;}
    public string lastname {get; private set;}
    public int age {get; private set;}

    public Student(string id,string firstname, string lastname, int age)
    {
        this.FirstName = firstname;
        this.lastname = lastname;
        this.age = age;
    }

    public abstract void calculatePayment();

}

以及以下子类:

public class InternationalStudent:Student
{
    public bool inviteOrientation {get; private set;}

    public InternationalStudent(string interID,string first, string last, int age, bool inviteOrientation)
        :base(interID,first,last,age)
    {
        this.inviteOrientation = inviteOrientation;

    }

    public override void calculatePayment()
    {
       //implementation left out
    }

}

主要

InternationalStudent svetlana = new InternationalStudent("Inter-100""Svetlana","Rosemond",22,true);

InternationalStudent checkEq = new InternationalStudent("Inter-101","Trisha","Rosemond",22,true);

问题:

我如何正确在我的子类中实现我的equalsTo方法?我已经reading here但我很困惑,因为有些答案表明子类不应该知道父类的成员。

如果我想在子类中实现IEquality,那么svetlana.Equals(checkEq);返回false,我该怎么做呢?

根据注释,使对象等于的是ID,名字和姓氏是否相同。

2 个答案:

答案 0 :(得分:2)

  

我感到困惑,因为有些答案表明子类不应该知道父类的成员。

你有倒退。子类完全了解所有非私有父类成员。

  

如何在子类中正确实现我的equalsTo方法?

什么定义"平等"在你的子类?通常情况下,它是属性值的组合,但大多数相关属性都在父类上,因此两个"学生"使用相同的名字,姓氏,年龄为"等于"?

public override bool Equals(object obj)
{
    var student = obj as InternationalStudent;

    if (student == null)
    {
        return false;
    } 

    return this.FirstName == student.FirstName &&
           this.lastname  == student.lastname &&
           this.age       == student.age;
}

但是,由于所有[有问题的属性都是继承的,也许这属于父类而不是子类。

答案 1 :(得分:2)

在基类中定义Equals,然后从子类

中调用它
public override bool Equals(object obj) {
    var other = obs as InternationalStudent;
    return other!= null && base.Equals(obj) && other.inviteOrientation == this.inviteOrientation;
}