在通用字典中找不到密钥[重复]

问题描述 投票:1回答:3

我无法通过密钥找到字典条目。我有一个如下界面:

public interface IFieldLookup
{
    string FileName { get; set; }
    string FieldName { get; set; }
}

然后我有一个这样的字典:

Dictionary<IFieldLookup, IField> fd

当我尝试通过键从字典中检索元素时,我得到一个KeyNotFoundException。我假设我必须实现某种类型的比较 - 如果我的假设是正确的,那么在这种情况下实施比较的推荐方法是什么?

c# generics
3个回答
1
投票

由于这是一个接口而不是类,因此您必须为实现接口的每个类定义相等运算符。那些运营商需要一直运营。 (如果它是一个类而不是一个接口,这会好得多。)

您必须在每个类上覆盖Equals(object)GetHashCode()方法。

可能是这样的:

public override bool Equals(object obj)
{
   IFieldLookup other = obj as IFieldLookup;
   if (other == null)
        return false;
   return other.FileName.Equals(this.FileName) && other.FieldName.Equals(this.FieldName);
}

public override int GetHashCode()
{
    return FileName.GetHashCode() + FieldName.GetHashCode();
}

或这个:

public override bool Equals(object obj)
{
   IFieldLookup other = obj as IFieldLookup;
   if (other == null)
        return false;
   return other.FileName.Equals(this.FileName, StringComparison.InvariantCultureIgnoreCase) && other.FieldName.Equals(this.FieldName, StringComparison.InvariantCultureIgnoreCase);
}

public override int GetHashCode()
{
    return StringComparer.InvariantCulture.GetHashCode(FileName) +
           StringComparer.InvariantCulture.GetHashCode(FieldName);
}

取决于您希望它的行为方式。


5
投票

使用ContainsKey并在键类上覆盖equals

好吧,让我们说这是我们的关键课程:

class Key
{
  public int KeyValue;
  public override Equals(object o)
  {
    return ((Key)o).KeyValue == KeyValue);
  }
}

现在让我们使用该类作为键

Dictonary<Key, string> dict = new Dictonary<Key, string>();
Key k = new Key();
k.KeyValue = 123;
dict.Add(k, "Save me!");
Key k2 = new Key();
k2.KeyValue = 123;
if (dict.ContainsKey(k2))
{
  string value = dict[k2];
}

1
投票

为密钥类型实现IEqualityComparer<T>的实例(推荐通过从EqualityComparer<T>派生,以便自动实现IEqualityComparer),并将实例传递给字典构造函数。这样,您可以跨接口的多个实现一致地实现比较。

© www.soinside.com 2019 - 2024. All rights reserved.