简体   繁体   中英

Why does overriding GetHashCode() block INotifyPropertyChanged?

I have a dead simple view model that inherits from INotifyPropertyChanged . After attempting to create some automated tests for this view model, I ended up overriding Equals() and GetHashCode() . My tests passed, so I was a happy camper.

However, now my Windows Forms data bindings aren't reacting to when a property in my view model changes. If I comment my GetHashCode() implementation all works as expected, except for my tests.

Here is my implementation:

public override int GetHashCode()
{
    unchecked
    {
        var hashCode = (_subject != null ? _subject.GetHashCode() : 0);
        hashCode = (hashCode * 397) ^ (_message != null ? _message.GetHashCode() : 0);
        hashCode = (hashCode * 397) ^
                   (_body != null ? _body.GetHashCode() : 0);
        return hashCode;
    }
}

This is simply what ReSharper generated for me.

Why does overriding GetHashCode() stop my data bindings from picking up on my view model changes despite me calling the PropertyChanged event?

I always try to avoid adding code to production code that is solely for testing purposes. So since you implemented Equals and GetHashCode for testing purposes, would it be possible to implement IEqualityComparer<T> and use that in your unit tests to performs the assertions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM