2016-07-01 3 views
1

私は次のテストの例があります。OrderRuleクラスには、次のさ...オブジェクトがIEquatableを実装している場合、Equal Collectionはfalseを返しますか?

変数rが真であるが、Assert.Equalが偽の

var a = new List<OrderRule> { 
    new OrderRule("name", OrderDirection.Ascending), 
    new OrderRule("age", OrderDirection.Descending) 
}; 

var b = new List<OrderRule> { 
    new OrderRule("name", OrderDirection.Ascending), 
    new OrderRule("age", OrderDirection.Descending) 
}; 

var r = a.SequenceEqual(b); 
Assert.Equal(a, b); 

を:

public class OrderRule : IEquatable<OrderRule> { 

    public OrderDirection Direction { get; } 
    public String Property { get; } 

    public OrderRule(String property, OrderDirection direction) { 
    Direction = direction; 
    Property = property; 
    } 

    public Boolean Equals(OrderRule other) { 
    if (other == null) 
     return false; 
    return Property.Equals(other.Property) && Direction.Equals(other.Direction); 
    } 

    public override Boolean Equals(Object obj) { 
    if (ReferenceEquals(null, obj)) 
     return false; 
    if (ReferenceEquals(this, obj)) 
     return true; 
    if (obj.GetType() != GetType()) 
     return false; 
    return Equals(obj as IncludeRule); 
    } 

    public override Int32 GetHashCode() { 
    return HashCode.Of(Property).And(Direction); 
    } 
} 

public enum OrderDirection { ASC, DESC } 

がありますEqualsをオーバーライドしてIEquatableを実装するときのAssert.Equalの問題

UPDATE - 私の側で期待どおりのhashCodeヘルパー

public struct HashCode { 

    private readonly Int32 Value; 

    private HashCode(Int32 value) { 
    Value = value; 
    } 

    public static implicit operator Int32(HashCode hashCode) { 
    return hashCode.Value; 
    } 

    public static HashCode Of<T>(T item) { 
    return new HashCode(GetHashCode(item)); 
    } 

    public HashCode And<T>(T item) { 
    return new HashCode(CombineHashCodes(Value, GetHashCode(item))); 
    } 

    public HashCode AndEach<T>(IEnumerable<T> items) {  
    Int32 hashCode = items.Select(x => GetHashCode(x)).Aggregate((x, y) => CombineHashCodes(x, y)); 
    return new HashCode(CombineHashCodes(Value, hashCode)); 
    } 

    private static Int32 CombineHashCodes(Int32 x, Int32 y) { 
    unchecked {   
     return ((x << 5) + x)^y; 
    } 
    } 

    private static Int32 GetHashCode<T>(T item) { 
    return item == null ? 0 : item.GetHashCode(); 
    } 

} 
+1

あなたのコードは私の側で期待通りに動作します(固定コンパイルエラー - 'IncludeRule'が' Equals' + 'OrderDirection'列挙メンバの' OrderRule'に変更されました) –

+0

ああ、それは逃しました! Damm Copy Right ...答えとしてあなたの説明を追加して、それをマークしますか? –

答えて

2

あなたのコードは動作します。私はコンパイルエラーを修正しました。IncludeRuleOrderRuleに変更されました。Equalsには、OrderDirection列挙メンバも固定されています。

+0

GetHashCodeをコードに変更しましたが、機能しませんでした。ところで、私はちょうど私のGetHashCodeヘルパーを追加しました。そこに何か間違いがありますか?しかし、とにかく、私はあなたのコードを試して以来、それはありません。 –

関連する問題