Custom Class used as key in Dictionary but key not found

前端 未结 4 728
忘了有多久
忘了有多久 2020-12-19 02:03

I have a class, show below, which is used as a key in a Dictionary I\'m having issues when trying to find any key within this diction

4条回答
  •  没有蜡笔的小新
    2020-12-19 02:30

    It looks like you're comparing two strings. Iirc, when using .Equals(), you are comparing the reference of the strings, not the actual contents. To implement an EqualityComparer that works with strings, you would want to use the String.Compare() method.

    public class EqualityComparer : IEqualityComparer
    {
         public bool Equals(ValuesAandB x, ValuesAandB y)
         {
              return ((String.Compare(x.valueA,y.valueA) == 0) &&
                (String.Compare(x.valueB, y.valueB) == 0));
         }
         // gethashcode stuff here
    }
    

    I could be a little off with the code, that should get you close...

提交回复
热议问题