📅  最后修改于: 2020-11-01 03:08:28             🧑  作者: Mango
C#字典初始化程序是一项用于初始化字典元素的功能。字典是元素的集合。它在键和值对中存储元素。
字典初始化程序使用花括号({})括起键和值对。
让我们看一个例子,其中我们初始化每个键的值。
using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
class DictionaryInitializer
{
public static void Main(string[] args)
{
Dictionary dictionary = new Dictionary()
{
[1] = "Irfan",
[2] = "Ravi",
[3] = "Peter"
};
foreach (KeyValuePair kv in dictionary)
{
Console.WriteLine("{ Key = " + kv.Key + " Value = " +kv.Value+" }");
}
}
}
}
输出:
{ Key = 1 Value = Irfan }
{ Key = 2 Value = Ravi }
{ Key = 3 Value = Peter }
在此示例中,我们将学生数据存储到字典中。我们正在使用字典初始化程序来存储学生数据。请参见以下示例。
using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
class DictionaryInitializer
{
public static void Main(string[] args)
{
Dictionary dictionary = new Dictionary()
{
{ 1, new Student(){ ID = 101, Name = "Rahul Kumar", Email = "rahul@example.com"} },
{ 2, new Student(){ ID = 102, Name = "Peter", Email = "peter@example.com"} },
{ 3, new Student(){ ID = 103, Name = "Irfan", Email = "irfan@abc.com"} }
};
foreach (KeyValuePair kv in dictionary)
{
Console.WriteLine("Key = "+kv.Key + " Value = {" + kv.Value.ID +", "+ kv.Value.Name +", "+kv.Value.Email+"}");
}
}
}
}
输出:
Key = 1 Value = {101, Rahul Kumar, rahul@example.com}
Key = 2 Value = {102, Peter, peter@example.com}
Key = 3 Value = {103, Irfan, irfan@abc.com}