辞書<>にアイテムを安全に追加するよりエレガントな方法はありますか?
キー/オブジェクトのペアをディクショナリに追加する必要がありますが、最初にキーがすでに存在するかどうかを最初に確認する必要があります。そうでない場合は、「キーはすでにディクショナリに存在しています」エラーが発生します。以下のコードはこれを解決しますが、不格好です。 このような文字列ヘルパーメソッドを作成せずにこれを行うよりエレガントな方法は何ですか? 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); } Console.ReadLine(); } …