C# 字典找不到 HashSet<enum> 类型的键
C# Dictionary can't find Key of type HashSet<enum>
private Dictionary<HashSet<Flags>, int> dict;
在开始时使用 Unity 检查器填充字典
public enum Flags
{
flag1,
flag2,
flag3
}
迭代字典确认它包含用于访问的相同哈希集,但尝试使用密钥访问总是 returns KeyNotFoundException。使用 ContainsKey
手动测试也 returns false。
好吧,默认情况下 .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");
如果你想通过值进行比较,你应该实现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;
}
}
并使用它:
private Dictionary<HashSet<Flags>, int> dict =
Dictionary<HashSet<Flags>, int>(new HashSetComparer<Flags>());
private Dictionary<HashSet<Flags>, int> dict;
在开始时使用 Unity 检查器填充字典
public enum Flags
{
flag1,
flag2,
flag3
}
迭代字典确认它包含用于访问的相同哈希集,但尝试使用密钥访问总是 returns KeyNotFoundException。使用 ContainsKey
手动测试也 returns false。
好吧,默认情况下 .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");
如果你想通过值进行比较,你应该实现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;
}
}
并使用它:
private Dictionary<HashSet<Flags>, int> dict =
Dictionary<HashSet<Flags>, int>(new HashSetComparer<Flags>());