教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 C#泛型学习笔记

C#泛型学习笔记

发布时间:2016-03-12   编辑:jiaochengji.com
泛型是2.0新增的功能,常见用途是泛型集合,命名空间System.Collections.Generic 中包含了一些基于泛型的集合类,使用泛型集合类可以提供更高的类型安全性,更高的性能,避免了非泛型集合的重复的装箱和拆箱。

很多非泛型集合类都有对应的泛型集合类,最好还是养成用泛型集合类的好习惯,它不但性能上好而且功能上要比非泛型类更齐全。

以下是常用的非C#泛型集合类以及对应的泛型集合类:
非泛型集合类 泛型集合类
ArrayList List<T>
HashTable DIctionary<T>
Queue Queue<T>
Stack Stack<T>
SortedList SortedList<T>

在1.1(C#2003中)用的比较多的集合类(非泛型集合)主要有  ArrayList类 和 HashTable类。后来2.0(C#2005中)增加了泛型功能,请通过下列代码段来理解泛型的优点:
 

复制代码 代码示例:
//c#1.1版本(NET2003)
System.Collections.ArrayList arrList = new System.Collections.ArrayList();
arrList.Add(2);//int ArrayList.Add(object value)
arrList.Add("this is a test!");//int ArrayList.Add(object value)
arrList.Add(DateTime.Now);//int ArrayList.Add(object value)
int result;
for (int i = 0; i < arrList.Count; i++)
{
result += int.Parse(arrList[i].ToString());//发生InvalidCastException异常
}
/*将光标放到Add方法上时,显示“int ArrayList.Add(object value)”,表明参数需要OBJECT类型的;
*ArrayList虽然可以操作任何类型(int,string,datetime)的数据,但是,在添加时它们都需要被强制装箱成object,在读取时还要强制拆箱,
* 装拆箱的操作,对于几百条以上的大量数据来说对性能影响极大。
*/
 
//c#2.0版本(NET2005)
System.Collections.Generic.List<int> arrListInt = new List<int>();
arrListInt.Add(2);//void List<int>.Add(int item)
 
System.Collections.Generic.List<string> arrListString = new List<string>();
arrListString.Add("this is a test!");//void List<string>.Add(string item)
int result;
for (int i = 0; i < arrListInt.Count; i++)
{
result += arrListInt[i];
}
 
System.Collections.Generic.List<DateTime> arrListDateTime = new List<DateTime>();
arrListDateTime.Add(DateTime.Now);//void List<DateTime>.Add(DateTime item)
/*将光标放到Add方法上时,可以看出所需参数类型恰好是用户提供的*/
 

 
说明:
对于客户端代码,与ArrayList 相比,使用List (T) 时添加的唯一语法是声明和实例化中的类型参数。
虽然这种方式稍微增加了编码的复杂性,但好处是可以创建一个比ArrayList 更安全并且速度更快的列表。

另外,假设想存储某种特定类型的数据(例如Int型),如果使用ArrayList,将用户添加的所有类型的数据都强制转换成object类型,导致编译器也无法识别,只有当运行时才能发现错误;而泛型集合List<T>则在编译时就会及时发现错误。

希望以上的介绍,对大家有所帮助。

您可能感兴趣的文章:
C#泛型:泛型特点、泛型继承、泛型接口、泛型委托学习笔记
C#泛型学习笔记
Golang中对interface{}做type assertion和type switch学习笔记
C# 多线程复制文件并显示进度条的代码
java学习笔记之泛型用法
C#学习笔记之匿名类型
C# 泛型类与泛型函数的实例学习
Java 和 C/C 中的char 类型长度学习笔记
C#泛型编程实例详解
C#泛型与非泛型性能比较 类型安全的实例代码

[关闭]
~ ~