本文主要是介绍Dictionary的TryGetValue方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这个方法时常会用到,而且很有效。TryGetValue:获取与指定的键相关联的值
比如我们读取一个xml文件,让后将其写入到Dictionary中存储:
- private static Dictionary<string, string> SqlKeyValues = null;
- /// <summary>
- /// 必要用户字段及别名
- /// </summary>
- internal static void InitUserFields(XmlDocument xml)
- {
- LoadXml(xml);
- XmlNode fields = xml.SelectSingleNode("/configs/users/fields");
- UserFields = new Dictionary<string, string>();
- if (fields.ChildNodes.Count > 0)
- {
- foreach (XmlNode n in fields.ChildNodes)
- {
- if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "item")
- {
- XmlAttribute fieldName = n.Attributes["name"];
- UserFields.Add(fieldName.Value, n.InnerXml);
- }
- }
- }
- }
我们可以通过下面方面来获取对应key的值
- public static string GetUserField(string fieldName)
- {
- string finfo = "";
- UserFields.TryGetValue(fieldName, out finfo);
- return finfo;
- }
- Dictionary<string, string> dic = new Dictionary<string, string>();
- dic.Add("aaa", "123");
- dic.Add("bbb", "456");
- dic.Add("ccc", "789");
- dic.Add("ddd", "321");
- string outStr = "999";
- dic.TryGetValue("ttt", out outStr);
- Response.Write(outStr + "<br />");
- dic.TryGetValue("bbb", out outStr);
- Response.Write(outStr + "<br />");
- //Response.Write(dic["ttt"] + "<br />");
这篇关于Dictionary的TryGetValue方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!