简体   繁体   中英

C# Dictionary can't find Key of type HashSet<enum>

private Dictionary<HashSet<Flags>, int> dict;

The dictionary is populated at Start using the Unity inspector

public enum Flags
{
    flag1,
    flag2,
    flag3
}

Iterating the dictionary confirms it contains the same hashset being used to access, but attempting to access with the key always returns a KeyNotFoundException. Manually testing with ContainsKey also returns false.

Well, .Net by default compare classes by references, eg

// A and B has same values, but different references
var A = new HashSet<Flags>() { Flags.flag1 };
var B = new HashSet<Flags>() { Flags.flag1 };

// Not Equals, since A and B doesn't share the same reference:
if (A.Equals(B)) 
  Console.Write("Equals");
else
  Console.Write("Not Equals");

If you want to compare by values , you should implement IEqualityComparer<T> interface:

    public class HashSetComparer<T> : IEqualityComparer<HashSet<T>> {
      public bool Equals(HashSet<T> left, HashSet<T> right) {
        if (ReferenceEquals(left, right))
          return true;
        if (left == null || right == null)
          return false;

        return left.SetEquals(right);
      }

      public int GetHashCode(HashSet<T> item) {
        return item == null ? -1 : item.Count;
      }
    }

And use it:

private Dictionary<HashSet<Flags>, int> dict = 
  Dictionary<HashSet<Flags>, int>(new HashSetComparer<Flags>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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