无法在通用字典中找到关键字

时间:2010-03-05 18:44:30

标签: c# generics

我无法按键找到词典条目。我有一个如下界面:

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

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

Dictionary<IFieldLookup, IField> fd

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

3 个答案:

答案 0 :(得分: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 :(得分: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);
}

取决于您的行为方式。

答案 2 :(得分:1)

为密钥类型实现IEqualityComparer<T>的实例(推荐自EqualityComparer<T>推导其IEqualityComparer的自动实现),并将实例传递给字典构造函数。这样,您就可以在界面的多个实现中一致地实现比较。