开发手册 欢迎您!
软件开发者资料库

.NET(C#)中new Dictionary(字典)初始化值(initializer默认值)

本文主要介绍在C#中new一个字典对象时,怎么指定字典的默认值。

1、C# 4.0中指定默认值的方法

class StudentName
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
}
Dictionary students = new Dictionary()
{
{ 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}}
};
//C# 4.0Dictionary myDict = new Dictionary { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" } };Dictionary> myDictList = new Dictionary> { { "key1", new List () { "value1" } }, { "key2", new List () { "value2" } }, { "key3", new List () { "value3" } } };

2、C# 6.0中指定默认值的方法

class StudentName
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
}
Dictionary students = new Dictionary () {
[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 }
};
//C# 6.0Dictionary dic = new Dictionary { ["key1"] = "value1", ["key2"] = "value2", ["key3"] = "value3" };Dictionary> dicList = new Dictionary> { ["key1"] = new List () { "value1" }, ["key2"] = new List () { "value2" }, ["key3"] = new List () { "value3" } };