在 Sub Class 中正确实现 Equals 和 GetHashCode

Properly Implement Equals and GetHashCode in Sub Class

假设我有以下摘要 Class 学生:

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();

}

和以下子class:

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);

问题:

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

如果我想在子class中实现IEquality,让svetlana.Equals(checkEq); returns false,我该怎么办呢?

根据评论,如果 ID、名字和姓氏相同,则对象相等。

I'm confused because some answers indicate that a subclass shouldn't know the members of the parent class.

你说反了。 subclass 完全了解所有非私有父 class 成员。

How would I properly implement my equalsTo method inside my subclass?

什么定义了你的子class中的"equality"?通常它是 属性 值的组合,但大多数相关属性都在父 class 上,所以两个具有相同名字、姓氏、年龄的 "students" 会是 "equal"?

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;
}

但是,由于所有[有问题的属性都是继承的,所以这可能属于父 class 而不是子 class。

在基 class 中定义 Equals,然后从子 class 中调用它

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