简体   繁体   English

用于输入字典的自定义相等比较器

[英]Custom equality comparer for Type in dictionary

Since Int32 is a Object , I want this to print "True"由于Int32是一个Object ,我希望它打印“True”

    Dictionary<Type, string> dict = new Dictionary<Type, string>(new MyComparer());
    dict[typeof(object)] = "Hello";

    Console.WriteLine(dict.ContainsKey(typeof(int))); // currently prints false :(

Here's the comparer I tried:这是我尝试过的比较器:

    public class MyComparer : IEqualityComparer<Type>
    {
        public bool Equals(Type x, Type y)
        {
            return y.IsAssignableFrom(x);
        }

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

But it's not working.但它不起作用。 I'm not quite sure what to return in GetHashCode - I know it's wrong cause when debugging I'm not even reaching Equals - Any idea how to write this correctly?我不太确定在GetHashCode返回什么 - 我知道调试时这是错误的原因我什至没有达到Equals - 知道如何正确编写它吗? Thanks.谢谢。

That simply is not a valid comparer for a dictionary, and the result is not well-defined.这根本不是字典的有效比较器,结果也没有明确定义。 Equality comparisons should be commutative, specifically a eq b if and only if b eq a .相等比较应该是可交换的,特别a eq b当且仅当b eq a That does not apply in your case.这不适用于您的情况。 Likewise, a valid hash-code implementation states that:同样,有效的哈希码实现声明:

  • if two hashes are non-equal, the two values are non-equal如果两个散列不相等,则两个值不相等
  • two equal values must have the same hash-code两个相等的值必须具有相同的哈希码

That fails too.那也失败了。

Basically, that isn't going to work.基本上,这是行不通的。

Specifically,from MSDN :具体来说,来自 MSDN

Notes to Implementers给实施者的注意事项

Implementations are required to ensure that if the Equals method returns true for two objects x and y, then the value returned by the GetHashCode method for x must equal the value returned for y.实现需要确保如果 Equals 方法对两个对象 x 和 y 返回true ,则 GetHashCode 方法为 x 返回的值必须等于为 y 返回的值。

The Equals method is reflexive, symmetric, and transitive. Equals 方法是自反的、对称的和可传递的。 That is, it returns true if used to compare an object with itself;也就是说,如果用于将对象与自身进行比较,则返回true true for two objects x and y if it is true for y and x;两个对象的x和y,如果它是用于y和x; and true for two objects x and z if it is true for x and y and also true for y and z.真正的两个对象x和z如果是Y和Z x和y的真实,也是如此

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

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