字典中Type的自定义相等比较器 [英] Custom equality comparer for Type in dictionary
问题描述
由于Int32
是 Object
,我希望此打印"True"
Since Int32
is a Object
, I want this to print "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();
}
}
但是它不起作用.我不太确定要在GetHashCode
中返回什么-我知道这是错误的原因,在调试时我什至没有达到Equals
-知道如何正确编写此代码吗?谢谢.
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? Thanks.
推荐答案
那根本不是字典的有效比较器,并且结果定义不明确.平等比较应该是可交换的,尤其是a eq b
当且仅当 b eq a
时.这不适用于您的情况.同样,有效的哈希码实现指出:
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
. That does not apply in your case. Likewise, a valid hash-code implementation states that:
- 如果两个散列不相等,则两个值不相等
- 两个相等的值必须具有相同的哈希码
那也失败了.
基本上,这是行不通的.
Basically, that isn't going to work.
具体来说,来自MSDN的:
Specifically, from MSDN:
实施者注意事项
要求执行以确保如果Equals方法为两个对象x和y返回 true ,则GetHashCode方法为x返回的值必须等于为y返回的值.
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.
等于方法是自反的,对称的和可传递的.也就是说,如果用于将对象与其自身进行比较,则返回 true ;否则,它将返回 true .如果两个对象x和y为 true ,则为 true ;和 true (如果两个对象x和z为 true 和y和z为 true ),则为 true .
The Equals method is reflexive, symmetric, and transitive. That is, it returns true if used to compare an object with itself; true for two objects x and y if it is true for y and x; and true for two objects x and z if it is true for x and y and also true for y and z.
这篇关于字典中Type的自定义相等比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!