简体   繁体   English

C# 字典找不到 HashSet 类型的 Key<enum></enum>

[英]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使用 Unity 检查器在开始时填充字典

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.迭代字典确认它包含用于访问的相同哈希集,但尝试使用密钥访问总是返回 KeyNotFoundException。 Manually testing with ContainsKey also returns false.使用ContainsKey手动测试也会返回 false。

Well, .Net by default compare classes by references, eg好吧,.Net 默认情况下通过引用比较类,例如

// 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:如果你想按比较,你应该实现IEqualityComparer<T>接口:

    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>());

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

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