C# 字典KeyNotFoundException未给出错误。。。为什么?

C# 字典KeyNotFoundException未给出错误。。。为什么?,c#,winforms,dictionary,C#,Winforms,Dictionary,这个问题不是它为什么会出错。。而是为什么它没有给出错误… 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"]); } privat

这个问题不是它为什么会出错。。而是为什么它没有给出错误…

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"]);
}
private void Form1\u加载(对象发送方,事件参数e)
{
Dictionary dic=新字典();
dic[“666字节”]=“我”;
MessageBox.Show(dic[“应该给出错误]);
}

这应该是一个错误,对吗?因为dic[“应该给出错误”]不存在,但没有给出错误(表单正常加载)。但是我可以用try..catch(KeyNotFoundException)block阻止它…为什么呢?

我怀疑您实际上没有运行
Form1\u 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"]);
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Windows.Forms;
课堂测试
{
静态void Main()
{
表单=新表单();
形式荷载+=形式1_荷载;
申请表格;
}
私有静态void Form1\u加载(对象发送方、事件参数e)
{
Dictionary dic=新字典();
dic[“666字节”]=“我”;
MessageBox.Show(dic[“应该给出错误]);
}
}
编译并运行它,你会看到一个异常对话框。

你必须读得更好。引述:

// If a key does not exist, setting the indexer for that key 
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
因此,当你调用dic[“应该给出错误”]时,程序会说,哦,这个键不存在,所以让我们创建一个。因此,它返回一个空字符串

Edit:好的,当您尝试获取不存在的密钥时,它不会返回空字符串,但是在某些情况下,load事件不能抛出异常。但是如果你保持原样,你应该有一个空的键值
“should\u give\u error”

我确实找到了答案(这是一个BUG,不是我期望的答案),下面是参考资料


  • 你确定你的表单加载事件已经连接好了吗?@JonSkeet:是的,我可以正常完成所有事情嗨,是的,我正在运行正确的表单加载事件。。。在这个活动中,我可以做所有其他的事情,比如更改背景颜色、显示其他Messagebox等等。@666bytes:你试过我给你的代码了吗?因为正如我所说,它肯定会为我显示一个例外框……事实并非如此,请检查我的答案