繁体   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