通过使用泛型类型参数 T,可以编写其他客户端代码能够使用的单个类,避免使用拆箱和装箱。
泛型类最常用于集合,如:链表集合List<T>,哈希表Hashtable等。
泛型列表list<T>位于using System.Collections.Generic命名空间中,是泛型
ArrayList 位于using System.Collections命名空间中,属于非泛型。
示例:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Collections.Generic; 3 public class StudyList1 4 { 5 public static void Main() 6 { 7 //初始化 8 List<Friend> list = new List<Friend>(); 9 //使用Add方法,添加元素 10 list.Add(new People(){Name = "瑞英"}); 11 list.Add(new People(){Name = "帅娜"}); 12 list.Add(new People(){Name = "三妮儿"}); 13 list.Add(new People(){Name = "老大"}); 14 list.Add(new People(){Name = "老二"}); 15 list.Add(new People(){Name = "老三"}); 16 list.Add(new People(){Name = "老四"}); 17 foreach(Friend f in list) 18 { 19 f.Happyness(); 20 } 21 } 22 } 23 //泛型接口 24 public interface Friend 25 { 26 void Happyness(); 27 } 28 //泛型继承 29 public class People:Friend 30 { 31 private string name = ""; 32 public string Name 33 { 34 get{return this.name;} 35 set{this.name = value;} 36 } 37 public void print() 38 { 39 Console.WriteLine(this.name); 40 } 41 public void Happyness() 42 { 43 Console.WriteLine("幸福,感恩!!!"); 44 } 45 }
泛型的优点:
1、泛型类和泛型方法同时具备可重用性、类型安全和效率。
2、泛型可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。