扩展方法
static class TestExtend { /// <summary> /// 判断是否有重复添加 /// </summary> /// <typeparam name="Tkey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <param name="value"></param> public static void AddSingle<Tkey, TValue>(this Dictionary<Tkey, TValue> dict, Tkey key, TValue value) { if (!dict.ContainsKey(key)) { dict.Add(key, value); } } /// <summary> /// 批量添加 /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dict"></param> /// <param name="keyValues"></param> public static void AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> keyValues) { foreach (var item in keyValues) { if (!dict.ContainsKey(item.Key)) dict[item.Key] = item.Value; } } /// <summary> /// 替换为指定的字符 /// </summary> /// <param name="str"></param> /// <param name="toChar"></param> /// <returns></returns> public static string ReplaceAToChar(this string str, string toChar) { return str.Replace("a", toChar); } /// <summary> /// 判断是否为数字 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool isNumerice(this string str) { Regex r = new Regex(@"^\d+(\.)?\d*$"); return (!r.IsMatch(str)) ? false : true; } }
static void Main(string[] args) { var model = new Dictionary<string, string>(); model.Add("001", "中国"); model.AddSingle("002", "美国");//判断重复添加值 var listModel = new Dictionary<string, string>(); listModel.AddRange(model);//批量添加Key/Value值 foreach (var item in listModel) { Console.WriteLine("Key:" + item.Key + " Value:" + item.Value); } string test = "jacky"; Console.WriteLine(test.ReplaceAToChar("@")); test = "12.88"; Console.WriteLine(test.isNumerice()); }
输出值: