[英]KeyNotFoundException in C#
I got an Exception here that doesn't find the rootPartNo
key in unbreakableLinkMap
dictionary. 我在这里遇到一个异常,该异常在
unbreakableLinkMap
字典中找不到rootPartNo
键。
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++;
}
How can I check/validate this? 我该如何检查/验证?
Usually you get this exception when the key specified for accessing an element in a collection does not match any key in the collection. 通常,当为访问集合中的元素而指定的键与集合中的任何键都不匹配时,会发生此异常。
I would suggest use the debugger and see you have that Key
available in the Dictionary
我建议使用调试器,看看
Dictionary
有可用的Key
If you are unsure of key existence, I would suggest writing defensive code, using ContainsKey
or TryGetValue
. 如果您不确定密钥是否存在,建议您使用
ContainsKey
或TryGetValue
编写防御性代码。
if (graph.unbreakableLinkMap.ContainsKey(key))
{
...
}
or 要么
if (graph.unbreakableLinkMap.TryGetValue(key, out spiritLinks)) {}
Well, you have to debug. 好吧,你必须调试。 Put a breakpoint on the
在断点上
var spiritLinks = graph.unbreakableLinkMap[rootPartNo];
line, run the routine and inspect the values of question: 行,运行例程并检查问题的值:
rootPartNo
as well as dictionary keys 以及字典键
graph.unbreakableLinkMap.Keys
If you can't use debugger for whatever reason, add debug output 如果由于某种原因无法使用调试器,请添加调试输出
...
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)));
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.