码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-09-26 14:23:34      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:

直接上代码:

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

  

 

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

标签:

原文地址:http://www.cnblogs.com/xiao9426926/p/5908910.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!