是否有更安全的方式将项目安全地添加到Dictionary <>中?
我需要将键/对象对添加到字典中,但是我当然需要首先检查该键是否已经存在,否则会收到“ 键在字典中已存在 ”错误。下面的代码解决了这个问题,但是很笨拙。 什么是更优雅的方法而不做这样的字符串助手方法呢? using System; using System.Collections.Generic; namespace TestDictStringObject { class Program { static void Main(string[] args) { Dictionary<string, object> currentViews = new Dictionary<string, object>(); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Customers", "view2"); StringHelpers.SafeDictionaryAdd(currentViews, "Employees", "view1"); StringHelpers.SafeDictionaryAdd(currentViews, "Reports", "view1"); foreach (KeyValuePair<string, object> pair in currentViews) { Console.WriteLine("{0} {1}", pair.Key, pair.Value); } …