按键获取字典值 [英] Get dictionary value by key

查看:37
本文介绍了按键获取字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过函数上的键获取字典值?

How can I get the dictionary value by a key on a function?

我的函数代码(以及我尝试的命令不起作用):

My function code (and the command I try doesn't work):

static void XML_Array(Dictionary<string, string> Data_Array)
{
    String xmlfile = Data_Array.TryGetValue("XML_File", out value);
}

我的按钮代码:

private void button2_Click(object sender, EventArgs e)
{
    Dictionary<string, string> Data_Array = new Dictionary<string, string>();
    Data_Array.Add("XML_File", "Settings.xml");

    XML_Array(Data_Array);
}

我希望 XML_Array 函数的变量是:

I want on the XML_Array function the variable to be:

string xmlfile = "Settings.xml":

推荐答案

就这么简单:

String xmlfile = Data_Array["XML_File"];

请注意,如果字典没有等于 "XML_File" 的键,则该代码将引发异常.如果你想先检查,你可以像这样使用 TryGetValue:

Note that if the dictionary doesn't have a key that equals "XML_File", that code will throw an exception. If you want to check first, you can use TryGetValue like this:

string xmlfile;
if (!Data_Array.TryGetValue("XML_File", out xmlfile)) {
   // the key isn't in the dictionary.
   return; // or whatever you want to do
}
// xmlfile is now equal to the value

这篇关于按键获取字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆