程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 對象初始值設定和集合初始值設定,對象集合

對象初始值設定和集合初始值設定,對象集合

編輯:關於.NET

對象初始值設定和集合初始值設定,對象集合


直接上代碼:

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

  

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved