c#字典可以找到类型的hashset< enum>

发布于 2025-01-23 09:06:04 字数 302 浏览 4 评论 0原文

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

使用Unity Inspector迭代该词典在开始时填充了字典,

public enum Flags
{
    flag1,
    flag2,
    flag3
}

该字典确认它包含用于访问的相同的标签,但尝试使用密钥访问始终返回KeynotFoundException。用containsKey手动测试也返回false。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眉黛浅 2025-01-30 09:06:04

好吧,默认情况下,.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");

如果要通过 value 进行比较,则应实现iequalityComparer&lt; t&gt;接口:

    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;
      }
    }

并使用它:并使用:

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

Well, .Net by default compare classes by references, e.g.

// 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>());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文