直接上代碼:
class Program { static void Main(string[] args) { StudentName student1 = new StudentName("Craig", "Playstead"); //對象初始值設定必須先訪問默認的實例構造函數 //使用對象初始值設定項初始化對象 StudentName student2 = new StudentName { FirstName = "Craig", LastName = "Playstead" }; StudentName student3 = new StudentName { ID = 183 }; StudentName student4 = new StudentName { FirstName = "Craig", LastName = "Playstead", ID = 116 }; Console.WriteLine(student1.ToString()); Console.WriteLine(student2.ToString()); Console.WriteLine(student3.ToString()); Console.WriteLine(student4.ToString()); Console.WriteLine(); //使用集合初始值設定項初始化字典 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 } } }; //字典的使用舉例 //foreach (KeyValuePair<int, StudentName> s in students) //{ // Console.WriteLine(s.Value .FirstName +" "+s.Value .LastName +" "+s.Value .ID ); //} Dictionary<int, StudentName>.KeyCollection keys = students.Keys; foreach (int s in keys ) { Console.WriteLine(students[s].ToString()); } Console.ReadKey(); } } public class StudentName { //如果這是默認構造函數是private,那麼對象初始值設定將會報錯 public StudentName () { FirstName = "Lily"; } public StudentName (string first,string last) { FirstName = first; LastName = last; } public string FirstName { get; set; } public string LastName { get; set; } public int ID { get; set; } public override string ToString() { return FirstName + " " +LastName +" "+ ID; } }