天天看點

C#泛型-使用泛型List

一、泛型的優點

性能高。從前面的例子可以看出使用不需進行類型轉換,可以避免裝箱和拆箱操作,提高性能。

類型安全。泛型集合對其存儲對象進行了類型限制,不是定義時聲明的類型,是無法存儲到泛型集合中的,保證了資料類型的安全。

代碼重用。使用泛型類型可以最大限度地重用代碼,保護類型的安全以及提高性能。

使用泛型

使用泛型可以定義泛型類,泛型接口,泛型方法等。.NET Framework類庫在System.Collection.Generic愈命名空間中包含幾個新的泛型集合類,List<T>和Dictionary<K,V>是其中非常重要的兩種,泛型接口IComparable<T>和IComparer<T>在實際中也有很重要的作用。

泛型集合List<T>

泛型最重要的應用就是集合操作,使用泛型集合可以提高代碼重用性,類型安全和更佳的性能。List<T>的用法和ArrayList相似,List<T>有更好的類型安全性,無須拆,裝箱。定義一個List<T>泛型集合的文法如下:

List<T> 集合名=new List<T>();

在泛型定義中,泛型類型參數“<T>”是必須指定的,其中T是定義泛型類時的占位符,其并不是一種類型,僅代表某種可能的類型。在定義時T會被使用的類型代替。泛型集合List<T>中隻能有一個參數類型,“<T>”中的T可以對集合中的元素類型進行限制。

注意:泛型集合必須執行個體化,執行個體化時和普通類執行個體化時相同,必須在後面加上“()”。

如定義一個學生類的List<T>,示例如下:

List<Student> students=new List<Student>();      

List<T>添加、删除、檢索元素的方法和ArrayList相似,明顯的特點是不需要像ArrayList那樣裝箱和拆箱。

using System;
 using System.Collections.Generic;
 using System.Collections;
 public class Student
 {
 public string Name
 {
    get;
    set;
 }
 public string Number
 {
    get;
    set;
 }
 public int Score
 {
    get;
    set;
 }
 }
 class Program
 {
 static void Main()
 {
    List < Student > students = new List < Student > ();
    Student stu1 = new Student();
    stu1.Name = "陸小鳳";
    stu1.Number = "0801";
    stu1.Score = 20;
    Student stu2 = new Student();
    stu2.Name = "西門吹雪";
    stu2.Number = "0802";
    stu2.Score = 23;
    students.Add(stu1);
    students.Add(stu2);
    Console.WriteLine("集合中的元素個數為{0}", students.Count);
    foreach (Student stu in students)
    {
     Console.WriteLine("\t{0}\t{1}\t{2}", stu.Name, stu.Number, stu.Score);
    }
    students.Remove(stu1);
    Console.WriteLine("集合中的元素個數為{0}", students.Count);
    Console.ReadLine();
 }
 }      

上面代碼定義了Student類型的List<T>泛型集合,其中的T被資料類型Student代替,這樣定義的集合隻能存儲Student類型的元素,保證了類型安全,周遊集合元素時,沒有經過拆箱操作,提高了性能。

using System;
 using System.Collections;
 using System.Collections.Generic;
 class Person
 {
 private string _name; //姓名
 private int _age; //年齡
 //建立Person對象
 public Person(string Name, int Age)
 {
    this._name = Name;
    this._age = Age;
 }
 //姓名
 public string Name
 {
    get
    {
     return _name;
    }
 }
 //年齡
 public int Age
 {
    get
    {
     return _age;
    }
 }
 }
 class Program
 {
 static void Main()
 {
    //建立Person對象
    Person p1 = new Person("張三", 30);
    Person p2 = new Person("李四", 20);
    Person p3 = new Person("王五", 50);
    //建立類型為Person的對象集合
    List < Person > persons = new List < Person > ();
    //将Person對象放入集合
    persons.Add(p1);
    persons.Add(p2);
    persons.Add(p3);
    //輸出第2個人的姓名
    Console.WriteLine(persons[1].Name);
    foreach (Person p in persons)
    {
     Console.WriteLine("\t{0}\t{1}", p.Name, p.Age);
    }
 }
 }      

繼續閱讀