简体   繁体   English

EqualityComparer <Type> GetHashCode和等于

[英]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. 我有一个带有自定义比较器的类型字典(字典),因为我们要存储2个给定类型之间的关系(用于MVVM模式),并且我需要帮助以寻求使自定义EqualityComparer正常工作的方法。

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 做一些研究后,我发现GetHashCode方法在Equals方法之前被调用,如何正确获得哈希码?预期的行为是,如果我尝试从字典中获取“ Square”,并且它具有“ GeometricShape”已经存在,它返回“ GeometricShape”的值,我找不到以给定预期结果的方式对其进行哈希处理的方法

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. 您不能使用将“ assignable from”用作等效操作的比较器。

Equals has particular rules assumed by classes that rely on it. Equals具有由依赖它的类假定的特定规则。 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(x)返回true。
x.Equals(y) returns the same value as y.Equals(x) x.Equals(y)返回与y.Equals(x)相同的值
if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true. 如果(x.Equals(y) && y.Equals(z))返回true,则x.Equals(z)返回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. 我不太确定如何解决您的特殊情况,也许如果您只需要将一种类型映射到另一种类型,则只需使用Dictionary<Type,Type>并将类型直接放入其中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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