【发布时间】:2014-11-21 22:25:40
【问题描述】:
我有一个将 Java 代码翻译成 C# 的任务。
这是以下 Java 代码:
public void addEdge(String node1, String node2) {
LinkedHashSet<String> adjacent = map.get(node1);
if(adjacent==null) {
adjacent = new LinkedHashSet();
map.put(node1, adjacent);
}
adjacent.add(node2);
}
这是我的 C# 代码:
public void addEdge(string node1, string node2) {
if (map.ContainsKey(node1)){
OrderedSet<string> adjacent = map[node1];
if (adjacent == null)
{
adjacent = new OrderedSet<string>();
map.Add(node1, adjacent);
}
adjacent.Add(node2);
}
else
throw new Exception(String.Format("Key {0} was not found", node1));
}
当我运行程序时,我得到以下异常: "字典中没有给定的键"
我的错误在哪里?
EDIT1: 我在这里声明了地图:
private Dictionary<string, OrderedSet<string>> map = new Dictionary<string, OrderedSet<string>>();
EDIT2: 我在以下行中得到异常:
map.Add(node1, adjacent);
【问题讨论】:
-
这是您的实际代码还是试图总结问题?我没有在任何地方看到
map声明,您的警卫应该阻止该异常。你确定这个方法中发生了异常吗? -
尝试总结问题。我在方法上方声明了它
-
也许是 TryGetValue 而不是 ContainsKey..但我不知道如何使用它
-
在调试器中单步执行,看看它是从哪一行抛出的
-
查看@Esteban Falcón 回答您的第二次编辑