簡體   English   中英

在子類中正確實現Equals和GetHashCode

[英]Properly Implement Equals and GetHashCode in Sub 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();

}

以及以下子類:

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方法? 我一直在這里閱讀,但我感到困惑,因為一些答案表明子類不應該知道父類的成員。

如果我想在子類中實現IEquality,那么svetlana.Equals(checkEq); 返回false,我該怎么辦?

根據注釋,使對象相等的是ID,名和姓是否相同。

我很困惑,因為一些答案表明子類不應該知道父類的成員。

你有倒退。 子類完全了解所有非私有父類成員。

如何在子類中正確實現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;
}

但是,由於所討論的所有屬性都是繼承的,所以也許它屬於父類而不是子類。

在基類中定義Equals,然后從子類中調用它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM