c# - 根据基类的 Equals() 使派生类相等

标签 c# inheritance casting

我有两个类,它们都派生自同一个父类:

public class People{
    public string BetterFoot;

    public override bool Equals(object obj){
        if (obj == null || this.GetType() != obj.GetType())
            return false;
        People o = (People)obj;
        return (this.BetterFoot == o.BetterFoot);
    }

public class LeftiesOrRighties: People{
    public string BetterHand;

    public override bool Equals(object obj){
        if (obj == null || this.GetType() != obj.GetType())
            return false;
        LeftiesOrRighties o = (LeftiesOrRighties)obj;
        return (this.BetterFoot == o.BetterFoot) &&
        (this.BetterHand == o.BetterHand)
    }
}

public class Ambidextrous: People{
    public string FavoriteHand;
}

(那里也有 GetHashCodes,但我知道它们可以工作。) 我想根据它们的根 Equals() 来比较它们的集合:

ThoseOneHanded = new List<LeftiesOrRighties>(){new LeftiesOrRighties(){BetterFoot = "L"}};
ThoseTwoHanded = new List<Ambidextrous>(){new Ambidextrous(){BetterFoot = "L"}};
//using NUnit
Assert.That ((People)ThoseOneHanded[0], Is.EqualTo((People)ThoseTwoHanded[0])));

不幸的是,这会返回false

为什么?难道类型转换不应该使它们(出于所有意图和目的,即使不完全相同)具有相同的类型,从而使用基本方法吗?如果不是,我如何真正将底层类型转换回 People

最佳答案

Cast 不会更改对象本身,因此 GetType 的结果将始终相同,因此您的 this.GetType() != obj.GetType() 将为 true,因此函数将返回 false。

以下逻辑可能会获得您想要的行为(并且您不需要强制转换为 People)

public class People 
{ 
    public string BetterFoot; 

    public override bool Equals(object obj)
    { 
        var o = obj as People;
        if (o == null) return false;
        return (this.BetterFoot = o.BetterFoot); 
} 

public class LeftiesOrRighties: People 
{ 
    public string BetterHand; 

    public override bool Equals(object obj) 
    { 
        var o = obj as LeftiesOrRighties; 
        if ( o == null) return base.Equals(obj);
        return (this.BetterFoot = o.BetterFoot) && (this.BetterHand = o.BetterHand) 
    } 
} 

public class Ambidextrous: People
{ 
    public string FavoriteHand; 
} 

关于c# - 根据基类的 Equals() 使派生类相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11479588/

相关文章:

c# - SQL查询的转换结果-System.InvalidCastException

c++ - 正确处理有符号和无符号值的比较

c# - 优雅的静态只读字符串集合分配

c# - 使用 iTextSharp 完成 PDF 中的复选框

generics - typescript ::抽象静态

c++ - 我有一个基类对象和派生类对象的 vector ,但我无法访问存储在 vector 中的派生对象继承的数据成员

c++ - 如何将指针序列化为 int 数组?

c# - 在源代码级别运行的 C# 静态源代码分析

c# - 如何验证您是否已连接到 C# 中的 MySQL 数据库?

c# - 泛型和类继承的混淆