【问题标题】:dictionary ContainsKey method字典 ContainsKey 方法
【发布时间】:2012-04-19 13:45:53
【问题描述】:

请解释为什么字典的 'getAt' 方法会失败

List<BString> infoKeys = new List<BString>(infoDict.Keys); 
if (infoKeys.Contains(TorrentFileKeyWords.FILES_KEY) == true) //"files"
{   
        List<BaseType> multiFiles = ((BList)dict[TorrentFileKeyWords.FILES_KEY]).Value; <<< this fails

所以 infoDict 是一个Dictionary&lt;String, BString&gt; 包含在 infoDict.Keys 上用于查找特定项目(BString 类型) 但是第 4 行失败了......没有感觉

我不使用 c#.. 所以我必须重写哪些方法(现在我有:GetHashCode、==、!= & equals)

【问题讨论】:

  • 你遇到了什么错误?
  • 您没有提供足够的代码来正确地帮助您,也没有出现错误。请阅读tinyurl.com/so-hints
  • 真正的类型是什么?如果infoDictDictionary&lt;String, BString&gt;,那么infoDict.Keys 将是String 的集合,而不是BString 的集合。

标签: c# dictionary contains


【解决方案1】:

我怀疑问题在于您在一个地方使用infoDict,而在另一个地方使用dict...

不清楚为什么要从infoDict 的键创建列表,而不是仅调用ContainsKey,或者(更好)使用TryGetValue 开始。此外,我建议反对为您的类型名称添加“B”前缀。

【讨论】:

    【解决方案2】:

    您无需将 Keys 复制到新列表即可执行查找。事实上,您可以检查该键是否存在于字典中使用TryGetValue 方法在单个操作中检索其关联值:

    BList bList;
    if (dict.TryGetValue(TorrentFileKeyWords.FILES_KEY, out bList))
    {
        List<BaseType> multiFiles = bList.Value;
        // use multiFiles here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2012-03-12
      相关资源
      最近更新 更多