Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4133233
  • 博文数量: 70
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1400
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-27 15:06
文章存档

2011年(2)

2010年(23)

2009年(21)

2008年(24)

我的朋友

分类:

2009-01-06 10:36:56

泛型是2.0新增的功能,它最常见的用途是泛型集合,命名空间System.Collections.Generic 中包含了一些基于泛型的集合类,使用泛型集合类可以提供更高的类型安全性,还有更高的性能,避免了非泛型集合的重复的装箱和拆箱。

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

     非泛型集合类

泛型集合类

ArrayList

List

HashTable

DIctionary

Queue

Queue

Stack

Stack

SortedList

SortedList

我们在1.1C#2003中)用的比较多的集合类(非泛型集合)主要有  ArrayList HashTable类。后来2.0C#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虽然可以操作任何类型(intstringdatetime)的数据,但是,在添加时它们都需要被强制装箱成object,在读取时还要强制拆箱,

* 装拆箱的操作,对于几百条以上的大量数据来说对性能影响极大。

*/

 

//c#2.0版本(NET2005

System.Collections.Generic.List<int> arrListInt = new List<int>();

arrListInt.Add(2);//void List.Add(int item)

 

System.Collections.Generic.List<string> arrListString = new List<string>();

arrListString.Add("this is a test!");//void List.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.Add(DateTime item)

/*将光标放到Add方法上时,可以看出所需参数类型恰好是用户提供的*/

 

通过上边例子可以看出,对于客户端代码,与ArrayList 相比,使用List (T) 时添加的唯一语法是声明和实例化中的类型参数。虽然这种方式稍微增加了编码的复杂性,但好处是您可以创建一个比ArrayList 更安全并且速度更快的列表。另外,假设我们想存储某种特定类型的数据(例如Int型),如果使用ArrayList,将用户添加的所有类型的数据都强制转换成object类型,导致编译器也无法识别,只有当运行时才能发现错误;而泛型集合List则在编译时就会及时发现错误。

阅读(781) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~