c#中的KeyNotFoundException

时间:2016-07-29 07:09:44

标签: c# dictionary

我在这里遇到了一个异常,但在rootPartNo词典中找不到unbreakableLinkMap键。

MyTree<IDbRecord> currentTree = PartHelper.GetTreeForRootId(succesorId, graph);
#region TreeSheet
string rootPartNo = currentTree.Root.Payload.GetField(Part.c_partNo).GetString();

//get spirit links
var spiritLinks = graph.unbreakableLinkMap[rootPartNo];
Worksheet treeWS = excel.Worksheets[2];
treeWS.Name = "Tree";
long displayedPartId = long.Parse(GetIdFromSession(Part.t_name));
int rowNo = 0;
bool bold = false;
Color color = Color.Black;
foreach (MyTreeNode<IDbRecord> node in currentTree.Root.DepthFirstNodeEnumerator)
{
    string partNo = node.Payload.GetField(Part.c_partNo).GetString();
    treeWS.Cells[rowNo, node.Depth].PutValue(partNo);
    bold = false;
    color = Color.Black;
    if (spiritLinks.Find(suc => suc.PartNo == partNo || suc.SucPartNo == partNo) != null)
    {
        color = Color.Red;
    }
    if (node.Payload.GetField(Part.c_id).GetInt64() == displayedPartId)
    {
        bold = true;
    }

    headerFStyle.Font.IsBold = bold;
    headerFStyle.Font.Color = color;
    treeWS.Cells[rowNo, node.Depth].SetStyle(headerFStyle);
    rowNo++;
}

我该如何检查/验证?

2 个答案:

答案 0 :(得分:3)

通常,当为访问集合中的元素指定的键匹配集合中的任何键时,会出现此异常。

我建议使用调试器,看看Key

中有Dictionary

如果您不确定密钥存在,我建议您使用ContainsKeyTryGetValue编写防御性密码。

if (graph.unbreakableLinkMap.ContainsKey(key)) 
{
     ... 
}

if((graph.unbreakableLinkMap.TryGetValue(key, out spiritLinks) {}

答案 1 :(得分:2)

好吧,你必须调试。

上设一个断点
  var spiritLinks = graph.unbreakableLinkMap[rootPartNo];

行,运行例程并检查问题的值:

  rootPartNo

以及字典键

  graph.unbreakableLinkMap.Keys

如果由于某种原因无法使用调试器,请添加调试输出

  ...
  string rootPartNo = currentTree.Root.Payload.GetField(Part.c_partNo).GetString();

  // Debug output: when key is not found, show additional info
  if (!graph.unbreakableLinkMap.ContainsKey[rootPartNo])
    MessageBox.Show(String.Format(
      "Key to find is \"{0}\" and keys in the dictionary are\r\n{1}", 
      rootPartNo, 
      String.Join(", ", graph.unbreakableLinkMap.Keys)));

  ...