【问题标题】:Dictionary KeyNotFoundException NOT giving error ... WHY?字典 KeyNotFoundException 没有给出错误...为什么?
【发布时间】:2013-12-02 20:47:40
【问题描述】:

这个问题不是为什么它给出错误..而是为什么它没有给出一个错误......

private void Form1_Load(object sender, EventArgs e)
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    dic["666bytes"] = "ME";
    MessageBox.Show(dic["should_give_error"]);
}

这应该会报错,对吧?因为 dic["should_give_error"] 不存在但它没有给出错误(表单正常加载)。但是我可以用 try..catch(KeyNotFoundException) 块来捕获它......怎么会?

【问题讨论】:

标签: c# winforms dictionary


【解决方案1】:

我怀疑你实际上并没有运行Form1_Load。这是一个简短但完整的程序,用于演示按预期抛出的异常:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

class Test
{
    static void Main()
    {
        Form form = new Form();
        form.Load += Form1_Load;
        Application.Run(form);
    }

    private static void Form1_Load(object sender, EventArgs e)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic["666bytes"] = "ME";
        MessageBox.Show(dic["should_give_error"]);
    }
}

编译并运行它,你会得到一个异常对话框。

【讨论】:

  • 嗨,是的,我正在运行正确的 Form_Load 事件...我可以在此事件期间执行所有其他操作,例如更改背景颜色、显示其他消息框等...
  • @666bytes:你试过我给出的代码了吗?因为正如我所说,它肯定为我显示了一个异常框......
【解决方案2】:

您必须更好地阅读documentation。引用:

// If a key does not exist, setting the indexer for that key 
// adds a new key/value pair.
openWith["doc"] = "winword.exe";

所以,当你调用dic["should_give_error"] 时,程序会运行,哦,那个键不存在,所以让我们创建一个。确实如此,并返回一个空字符串。

编辑:好的,当您尝试获取不存在的键时它不会返回空字符串,但加载事件在某些条件下无法抛出异常。但是,如果您保持原样,则键 "should_give_error" 应该有一个空值。

【讨论】:

  • 不是这样,请查看我的回答
【解决方案3】:

我确实找到了答案(这是一个 BUG,不是我期待的答案),这里是参考资料...

  1. Reference # 1
  2. Reference # 2
  3. Reference # 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-02
    • 2013-04-03
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2016-06-27
    • 2013-12-10
    • 1970-01-01
    相关资源
    最近更新 更多