简体   繁体   中英

EqualityComparer<Type> GetHashCode and Equals

i have a Dictionary of types (Dictionary) with a custom comparer, because we want to store relationships between 2 given types (for a MVVM pattern), and i need help comming up with a way to get custom EqualityComparer to work.

Doing some research i found that the GetHashCode method gets called before the Equals method, how can i get the hashcodes right?, the expected behavior it's that if i try to get a "Square" from my dictionary, and it has a "GeometricShape" already in it, it returns the value of the "GeometricShape", i can't find a way to hash it in a way that i gives the expected result

public class DictionaryComparer : EqualityComparer<Type>
{
    public override bool Equals(Type x, Type y)
    {            
        return x.IsAssignableFromType(y);
    }

    public override int GetHashCode(Type obj)
    {
        return obj.GetHashCode();
    }
}

You can't have comparer that uses "assignable from" as equivalency operation.

Equals has particular rules assumed by classes that rely on it. If you break the rules results of using such comparer would be essentially random shuffle.

See Guidelines for Overloading Equals()

x.Equals(x) returns true.
x.Equals(y) returns the same value as y.Equals(x)
if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.

I'm not really sure how to solve your particular case, possibly if you just need to map one type to another you just have Dictionary<Type,Type> and put types directly to it.

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