问题描述
我有一个类,在下面显示,它被用作字典< ValuesAandB,string>
中的一个键。在这本字典中找到任何键,它根本找不到。如您所见,我已经覆盖了等于
和 GetHashCode
。
I have a class, show below, which is used as a key in a Dictionary<ValuesAandB, string>
I'm having issues when trying to find any key within this dictionary, it never finds it at all. As you can see, I have overridden Equals
and GetHashCode
.
要查找我正在使用的密钥
To look for the key I'm using
ValuesAandB key = new ValuesAandB(A,B);
if (DictionaryName.ContainsKey(key)) {
...
}
还有什么我失踪的吗?任何人都可以指出我在做错什么?
Is there anything else that I'm missing? Can anyone point out what I'm doing wrong?
private class ValuesAandB {
public string valueA;
public string valueB;
// Constructor
public ValuesAandB (string valueAIn, string valueBIn) {
valueA = valueAIn;
valueB = ValueBIn;
}
public class EqualityComparer : IEqualityComparer<ValuesAandB> {
public bool Equals(ValuesAandB x, ValuesAandB y) {
return ((x.valueA.Equals(y.valueA)) && (x.valueB.Equals(y.valueB)));
}
public int GetHashCode(ValuesAandB x) {
return x.valueA.GetHashCode() ^ x.valueB.GetHashCode();
}
}
}
在任何人要求之前,是这些值在字典中!
And before anyone asks, yes the values are in the Dictionary!
推荐答案
你如何构建字典?您是否将自定义的平等比较器传递给其构造函数?
How are you constructing the dictionary? Are you passing your custom equality comparer in to its constructor?
这篇关于自定义类用作字典中的键,但未找到键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!