2

同じ親から派生した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ですか?

4

2 に答える 2

2

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; 
} 
于 2012-07-13T23:31:36.717 に答える
0

Bob Valeが指摘したように、castはタイプを変更しません。

.NET Framework全体で使用される標準ソリューションは、IEqualityComparerまたはその汎用バリアントを実装するカスタムオブジェクトを使用することです。次に、compare / findメソッドは2つのオブジェクト/コレクションを取得し、comparerを使用してカスタム比較を実行します。

つまり、多くのメソッドは、 Enumerable.DistinctLINQのようなオブジェクトを検索/フィルタリングするためにカスタム比較を行います

public static IEnumerable<TSource> Distinct<TSource>(
    this IEnumerable<TSource> source,
    IEqualityComparer<TSource> comparer
)

サンプル比較:

class Last3BitsComparer : IEqualityComparer<int>
{
    public bool Equals(int b1, int b2)
    {
        return (b1 & 3) == (b2 & 3);
    }
    public int GetHashCode(int bx)
    {
        return bx & 3;
    }
}
于 2012-07-14T00:01:51.360 に答える