C#拓展Dictionary的TryGetValue方法以及新增方法。
using System;
using System.Collections.Generic;namespace CSharpTest01
{public static class DictionaryExtension{public static string TryGetValue(this Dictionary<string, string> dic, string key){if (dic == null)throw new Exception("Dictionary is NULL.");string value = string.Empty;if (!dic.TryGetValue(key, out value))throw new Exception("The given key:" + key + " was not present in the dictionary.");return value;}public static string TryGetValueEx(this Dictionary<string, string> dic, string key){if (dic == null)throw new Exception("Dictionary is NULL.");string value = string.Empty;if (!dic.TryGetValue(key, out value))throw new Exception("The given key:" + key + " was not present in the dictionary.");return value;}}class Program{static void Main(string[] args){Dictionary<string, string> dic = new Dictionary<string, string>();dic.Add("id", "1");dic.Add("name", "kerven");try{string id = dic.TryGetValue("id");Console.WriteLine(id);string name = dic.TryGetValueEx("name");Console.WriteLine(name);}catch (Exception ex){Console.WriteLine(ex.Message);}Console.ReadLine();}}
}