1. 程式人生 > 其它 >泛型集合的由來和使用

泛型集合的由來和使用

泛型(Generic) 允許您延遲編寫類或方法中的程式設計元素的資料型別的規範,直到實際在程式中使用它的時候。換句話說,泛型允許您編寫一個可以與任何資料型別一起工作的類或方法。

泛型最常見的用途是建立集合類。

普通集合在使用用出現的問題:

class Teacher  //教師
{
    public Teacher(string name,double salary)
    {
        this.Name = name;
        this.Salary = salary;
    }
    public string Name { get; set; }   //姓名
    public double Salary { get; set; }  //工資
}
class Student	//學生
{
    public Student(string no,string name)
    {
        this.No = no;
        this.Name = name;
    }
    public string No { get; set; }  //學號
    public string Name { get; set; } //姓名
}
Student s1 = new Student("001","劉備");
Student s2 = new Student("002", "公孫贊");
Teacher t1 = new Teacher("盧值", 5000);
ArrayList list = new ArrayList();
list.Add(s1);
list.Add(s2);
list.Add(t1);

//集合元素的資料型別沒有要求一致,所以下面的程式會因為型別的原因報錯
foreach (Student item in list)
{
    Console.WriteLine(item.Name);
}

上述程式的foreach迴圈中會產生執行中錯誤,原因是集合中第三個物件不是Student物件,此處型別會出異常,由此我們得出:

(1)ArrayList型別不安全性,因為裡面什麼型別都可以存放。

(2)而泛型集合定義時必須指定集合中儲存資料的型別,正好解決了型別安全問題。

一、List泛型集合

List泛型集合使用方法和ArrayList集合類似,如下:

Student s1 = new Student("001","劉備");
Student s2 = new Student("002", "公孫贊");
Teacher t1 = new Teacher("盧值", 5000);
List<Student> list = new List<Student>();
list.Add(s1);
list.Add(s2);
list.Add(t1);  //此行程式碼編譯出錯,去掉此行程式碼,程式正常執行
foreach (Student item in list)
{
    Console.WriteLine(item.Name);
}

上述程式碼在新增集合元素的時候就會編譯出錯,保證的型別的安全。

List泛型集合常用屬性和方法如下:

屬性名 功能說明
Capacity 獲取或設定List可包含的元素個數
Count 獲取List實際包含的元素個數
方法名 功能說明
Add() 將元素新增到List結尾處
Insert() 將元素新增到List的指定索引處
Remove() 移除List指定的元素
RemoveAt() 移除List指定索引處元素
Clear() 清除List中所有元素
Sort() 對List中的元素排序
Reverse() 將List中的元素順序反轉
ToArray() 將List中的元素複製到陣列中

二、Dictionary泛型集合

Dictionary泛型集合使用方法和HashTable集合類似,並且Dictionary泛型集合和List泛型集合一樣,都是型別安全的,如下:

Student s1 = new Student("001","劉備");
Student s2 = new Student("002", "公孫贊");
Dictionary<string, Student> list = new Dictionary<string, Student>();
list.Add(s1.No, s1);
list.Add(s2.No, s2);
Console.WriteLine("顯示所有人員資訊:");
foreach (Student stu in list.Values)
{
	Console.Write(stu.Name+"  ");
}

Dictionary泛型集合常用屬性和方法如下:

屬性名 功能說明
Keys 獲取包含Dictionary<K,V>中所有鍵的ICollection (可以遍歷該屬性訪問集合中所有鍵)
Values 獲取包含Dictionary<K,V>中所有值的ICollection (可以遍歷該屬性訪問集合中所有值)
Count 獲取Dictionary<K,V>中鍵/值對的數目
方法名 功能說明
Add(object key, object value) 將帶有指定鍵和值的元素新增到Dictionary<K,V>中
Remove() 從Dictionary<K,V>中移除帶有指定鍵的元素
Clear() 移除Dictionary<K,V>中所有元素
ContainsKey() 確定Dictionary<K,V>中是否包含指定鍵
ContainsValue() 確定Dictionary<K,V>中是否包含指定值