同じ親から派生した2つのクラスがあります。
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
ですか?