在通用词典中找不到密钥 [英] Cannot Find Key in Generic Dictionary

查看:45
本文介绍了在通用词典中找不到密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过键找到字典条目.我有一个类似以下的界面:

I cannot find a dictionary entry by key. I have an interface like the following:

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

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

Then I have a dictionary like so:

Dictionary<IFieldLookup, IField> fd

当我尝试通过键从字典中检索元素时,出现KeyNotFoundException.我假设我必须执行某种类型的比较-如果我的假设正确,那么在这种情况下建议的比较方法是什么?

When I try to retrieve an element out of the dictionary by the key, I get a KeyNotFoundException. I am assuming that I have to implement some type of comparison - if my assumption is correct, what is the recommended way of implementing a comparison in this case?

推荐答案

由于这是一个接口而不是一个类,因此您必须为实现该接口的每个类定义相等运算符.这些操作员将需要始终如一地进行操作. (如果它是一个类而不是一个接口,那会更好.)

Since this is an interface rather than a class, you will have to define your equality operator for every class that implements the interface. And those operators will need to operate consistantly. (This would be much better if it were a class rather than an interface.)

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

You must override the Equals(object) and GetHashCode() methods on each class.

大概是这样的:

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

取决于您希望它的行为.

Depending on how you want it to behave.

这篇关于在通用词典中找不到密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆