• 泛型


    1: 当T为简单类型

             List<int> list = new List<int>();
                list.Add(1);
                list.Add(2);
                foreach (var va in list) //使用 foreach 语句
                {
                    Console.WriteLine(va);
    
                }
    
                for (int i = 0; i < list.Count; i++)   //使用 for 语句
                {
                    Console.WriteLine(list[i]);
                }        

    结果:

    2:当 T 为对象

    namespace fanxing
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Student> stu = new List<Student>();
    
                stu.Add(new Student("jack", 14));  // 将对象加入到泛型集合中
                stu.Add(new Student("jely", 15));
    
                foreach (Student s in stu)
                {
                    Console.WriteLine("{0},{1}", ((Student)s).StudentName, ((Student)s).Age);  // 先将 集合s 转为 类类型Student, 然后获取其属性值
                }
    
                for (int i = 0; i < stu.Count; i++)
                {
                    Console.WriteLine("{0},{1}", ((Student)stu[i]).StudentName, ((Student)stu[i]).Age);
                }
    
    
    
            }
    
            public class Student
            {
                private string studentName;
                private int age;
                public string StudentName
                {
                    get
                    {
                        return studentName;   //一定要有这句
                    }
                }
                public int Age
                {
                    get { return age; }
                }
                public Student(string sStudentName,int aAge)
                {
                    this.studentName = sStudentName;
                    this.age = aAge;
                }
            }
        }
    }

    从泛型集合中取出元素时不再需要进行拆箱操作(或显示类型转换)

    所以可以直接将两个输出改为(效果一样):

           foreach (Student dent in stu)
                {
                    Console.WriteLine(dent.StudentName);
                }
    
                for (int i = 0; i < stu.Count; i++)
                {
                    Console.WriteLine(stu[i].StudentName);
                }

    结果:

  • 相关阅读:
    2015上海网络赛 A Puzzled Elena
    容斥原理——uva 10325 The Lottery
    2015北京网络赛B题 Mission Impossible 6
    2015北京网络赛A题The Cats' Feeding Spots
    POJ3087——map——Shuffle'm Up
    POJ3126——BFS——Prime Path
    POJ1426——BFS——Find The Multiple
    算法总结——Prim
    算法总结——Dijkstra
    算法总结——Floyed
  • 原文地址:https://www.cnblogs.com/TangPro/p/3204314.html
Copyright © 2020-2023  润新知