首页 > 代码库 > 对象初始值设定和集合初始值设定

对象初始值设定和集合初始值设定

直接上代码:

    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;        }    }

  

 

对象初始值设定和集合初始值设定