12.泛型集合Dictionary
阿新 • • 發佈:2020-12-29
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2.泛型集合Dictionary
{
class Program
{
static void Main(string[] args)
{
//建立幾個學員物件
Student objstu1 = new Student(1001, "小王");
Student objstu2 = new Student(1002, "校長");
Student objstu3 = new Student(1003, "小李");
Student objstu4 = new Student(1004, "小劉");
//建立Dictionary泛型集合 Dictionary<int, Student> stus = new Dictionary<int, Student>(); stus.Add(1, objstu1); stus.Add(2, objstu2); stus.Add(3, objstu3); stus.Add(4, objstu4); //取出元素 int strId = stus[1].StudentId; string strName = stus[1].StudentName; //遍歷 //方法1 foreach (int key in stus.Keys) { Console.WriteLine(key); } //方法2 foreach (Student value in stus.Values) { Console.WriteLine(value.StudentName+"\t"+value.StudentId+"\t"+value.Age); } Console.Read(); } } class Student { public Student() { } /// <summary> /// 帶有引數的建構函式 /// </summary> /// <param name="stuId"></param> /// <param name="stuNmae"></param> public Student(int stuId, string stuNmae) { this.StudentId = stuId; this.StudentName = stuNmae; } public int StudentId { get; set; } public string StudentName { get; set; } public int Age { get; set; } }
}