导航

Dictionary的使用

Posted on 2012-10-09 10:25  杨彬Allen  阅读(181)  评论(0)    收藏  举报

  Dictionary结构也是由Key+Value组成:Dictionary<[key],[value]>。(这点和哈希表类似)

  Dictionary的特点是存入对象是需要与[key]值一一对应的存入该泛型,并通过唯一的[key]去找到对应的值。

  首先定义一个对象:Student,分别有学号,姓名,性别,年龄等属性。

    public class Student
    {
        //学号
        public string StudentID { get; set; }

        //姓名
        public string Name { get; set; }

        //性别:0=男 1=女
        public int Sex { get; set; }

        //年龄
        public int Age { get; set; }
    }

  再在button1_click事件中分别添加学生和查找学生。

        private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<string, Student> students = new Dictionary<string, Student>();

            //添加学生
            students.Add("001", new Student { StudentID = "001", Name = "", Sex = 0, Age = 20 });
            students.Add("002", new Student { StudentID = "002", Name = "", Sex = 0, Age = 21 });

            //查找学生
            Student s1 = students["001"];
            Student s3 = students["003"];//此处会报错,因为"003"是不存在的
        }

  另外虽然Dictionary和HashTable类似,但他们还是有不同之处的,在不同的场合合理的使用它们会达到更好的效果。