1、C# 4.0中指定默认值的方法
在 C# 4.0 中,可以使用集合初始化器语法来初始化 Dictionary<TKey, TValue>
对象。集合初始化器语法可以使用大括号括起来的一系列键值对来初始化字典。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { static void Main(string[] args) { //C# 4.0 Dictionary<string, string> myDict = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } }; Console.WriteLine(myDict); Dictionary<string, List<string>> myDictList = new Dictionary<string, List<string>> { { "key1", new List<string> () { "value1" } }, { "key2", new List<string> () { "value2" } }, { "key3", new List<string> () { "value3" } } }; Console.WriteLine(myDictList); Dictionary<int, StudentName> students = new Dictionary<int, StudentName>() { { 111, new StudentName {FirstName="Sachin", LastName ="Karnik", ID=211}}, { 112, new StudentName {FirstName="Dina", LastName ="Salimzianova", ID=317}}, { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID =198}} }; Console.WriteLine(students); } } class StudentName { public string FirstName { get; set; } public string LastName { get; set; } public int ID { get; set; } } }
2、C# 6.0中指定默认值的方法
在C# 6.0及之后的版本中,字典初始化可以更加简洁地通过索引器语法进行,这使得在声明并初始化一个Dictionary时代码更加简洁明了。这种方法不仅适用于字典,还适用于其他支持索引器的集合类型。这种初始化方式特别适合在需要预填充一些键值对到字典中的场景。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication { class Program { static void Main(string[] args) { Dictionary<int, StudentName> students = new Dictionary<int, StudentName>() { [111] = new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 }, [112] = new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 }, [113] = new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }; Console.WriteLine(students); //C# 6.0 Dictionary<string, string> dic = new Dictionary<string, string> { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3" }; Console.WriteLine(dic); Dictionary<string, List<string>> dicList = new Dictionary<string, List<string>> { ["key1"] = new List<string>() { "value1" }, ["key2"] = new List<string>() { "value2" }, ["key3"] = new List<string>() { "value3" } }; Console.WriteLine(dicList); } } class StudentName { public string FirstName { get; set; } public string LastName { get; set; } public int ID { get; set; } } }