C#泛型集合定义及使用

  • 内容
  • 评论
  • 相关

C# 语言中泛型集合是泛型中最常见的应用,主要用于约束集合中存放的元素。

由于在集合中能存放任意类型的值,在取值时经常会遇到数据类型转换异常的情况,因此推荐在定义集合时使用泛型集合。

前面《C# ArrayList》与《C# Hashtable》中已经介绍了非泛型集合中的 ArrayList、Hashtable。

非泛型集合中的 ArrayList、Hashtable 在泛型集合中分别使用 List<T> 和 Dictionary<K,V> 来表示,其他泛型集合均与非泛型集合一致。

下面以 List<T> 和 Dictionary<K,V> 为例介绍泛型集合的使用。

【实例 1】使用泛型集合 List<T> 实现对学生信息的添加和遍历。

根据题目要求,将学生信息定义为一个类,并在该类中定义学号、姓名、年龄属性。

在泛型集合 List<T> 中添加学生信息类的对象,并遍历该集合。实现的代码如下。

class Program
{
    static void Main(string[] args)
    {
        //定义泛型集合
        List<Student> list = new List<Student>();
        //向集合中存入3名学员
        list.Add(new Student(1, "小明", 20));
        list.Add(new Student(2, "小李", 21));
        list.Add(new Student(3, "小赵", 22));
        //遍历集合中的元素
        foreach(Student stu in list)
        {
            Console.WriteLine(stu);
        }
    }
}
class Student
{
    //提供有参构造方法,为属性赋值
    public Student(int id,string name,int age)
    {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    //学号
    public int id { get; set; }
    //姓名
    public string name { get; set; }
    //年龄
    public int age { get; set; }
    //重写ToString 方法
    public override string ToString()
    {
        return id + ":" + name + ":" + age;
    }
}

执行上面的代码,效果如下图所示。

List<T>泛型集合的使用

本文标题:C#泛型集合定义及使用

本文地址:https://www.hosteonscn.com/4852.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注