A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 丁海平 中级黑马   /  2013-8-27 20:32  /  1348 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

泛型集合中的泛型就是就是通过它来定义类型安全的数据类型,它最显著的特征就是创建了集合类,可以约束集合类的元素类型。今天就学习了list<T>和dictionary<T,V>两种泛型。
它的优点是:
1.泛型的性能高  没有装箱、拆箱的操作。因此也就不会发生类型转换。
2.类型安全  由于在定义时,就设定了数据的类型,对类型做了约束。不是此类型的数据无法添加到此集合。
这两大优点,是的泛型集合在编程是得到了广泛的应用。再加上它的使用和集合的区别不大,会使用集合就会使用它。
List<T>泛型集合是对数据类型做了约束,在使用它时,必须先进行实例化。
先定义了一个类:
public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Student(string name, int age)
        {
            this.Age = age;
            this.Name = name;
        }
    }
list<T>实例:
List<Student> stu = new List<Student>();
            Student stu1 = new Student("小华", 12);
            Student stu2 = new Student("小定", 12);
            Student stu3 = new Student("小砍", 12);
            Student stu4 = new Student("小苗", 12);
            stu.Add(stu1);
            stu.Add(stu2);
            stu.Add(stu3);
            stu.Add(stu4);
            foreach (Student student in stu)
            {
                Console.WriteLine("{0} {1}",student.Name,student.Age);
            }
            Console.ReadKey();
dictionary<K,V>泛型集合不仅对数据类型做了约束,他可以对类进行操作,遍历此集合时,是对它的value进行遍历。
还能通过关键字Key来访问集合。
Dictionary<string,Student> stu = new Dictionary<string,Student>();
            
            Student stu1 = new Student("小华", 12);
            Student stu2 = new Student("小定", 12);
            Student stu3 = new Student("小砍", 12);
            Student stu4 = new Student("小苗", 12);
            stu.Add(stu1.Name,stu1);
            stu.Add(stu2.Name,stu2);
            stu.Add(stu3.Name,stu3);
            stu.Add(stu4.Name,stu4);
            Student stu5 = stu["小华"];//能通过key关键字来访问
            foreach (Student student in stu.Values)
            {
                Console.WriteLine("{0} {1}  {2}",student.Name,student.Age,stu5.Age);
            }
            Console.ReadKey();

评分

参与人数 1技术分 +1 收起 理由
赵宗荣 + 1

查看全部评分

2 个回复

倒序浏览
嗯,总结的很好,泛型在项目中用的很多。
回复 使用道具 举报
值得学习ing!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马