C#泛型的优势

在C#中,使用泛型会获得以下优势:

减少装箱和拆箱操作,提高性能
可以进行编译时类型检查
举例说明:

使用非泛型的集合类,利用 .NET Framework 基类库中的 ArrayList 集合类。ArrayList 是一个使用起来非常方便的集合类,无需进行修改即可用来存储任何引用或值类型。

view plaincopy to clipboardprint?
// The .NET Framework 1.1 way to create a list:  
System.Collections.ArrayList list1 = new System.Collections.ArrayList();  
list1.Add(8);  
list1.Add("It is raining heavily outside."); 
// The .NET Framework 1.1 way to create a list:
System.Collections.ArrayList list1 = new System.Collections.ArrayList();
list1.Add(8);
list1.Add("It is raining heavily outside.");

但这种方便是需要付出代价的。添加到 ArrayList 中的任何引用或值类型都将隐式地向上强制转换为 Object。如果项是值类型,则必须在将其添加到列表中时进行装箱操作,在检索时进行取消装箱操作。强制转换以及装箱和取消装箱操作都会降低性能;尤其是在必须对大型集合进行循环访问的情况下,装箱和取消装箱的影响将非常明显。

另一个限制是缺少编译时类型检查;因为 ArrayList 将把所有项都强制转换为 Object,所以在编译时无法防止客户端代码执行以下操作:

view plaincopy to clipboardprint?
System.Collections.ArrayList list = new System.Collections.ArrayList();  
// Add an integer to the list.  
list.Add(8);  
// Add a string to the list. This will compile, but may cause an error later.  
list.Add("It is raining heavily outside.");  
 
int t = 0;  
// This causes an InvalidCastException to be returned.  
foreach (int x in list)  
{  
    t += x;  

System.Collections.ArrayList list = new System.Collections.ArrayList();
// Add an integer to the list.
list.Add(8);
// Add a string to the list. This will compile, but may cause an error later.
list.Add("It is raining heavily outside.");

int t = 0;
// This causes an InvalidCastException to be returned.
foreach (int x in list)
{
    t += x;
}

尽管将字符串和 int 组合在一个 ArrayList 中的做法在创建异类集合时是完全合法的,有时是有意图的,但这种做法更可能产生编程错误,并且直到运行时才能检测到此错误。


在 C# 语言的 1.0 和 1.1 版本中,只能通过编写自己的特定于类型的集合来避免 .NET Framework 基类库集合类中的通用代码的危险。当然,由于此类不可对多个数据类型重用,因此将丧失通用化的优点,并且您必须对要存储的每个类型重新编写该类。

ArrayList 和其他相似类真正需要的是:客户端代码基于每个实例指定这些类要使用的具体数据类型的方式。这样将不再需要向上强制转换为 T:System.Object,同时,也使得编译器可以进行类型检查。换句话说,ArrayList 需要一个 type parameter。这正是泛型所能提供的。在 N:System.Collections.Generic 命名空间的泛型 List<T> 集合中,向该集合添加项的操作类似于以下形式:

view plaincopy to clipboardprint?
// The .NET Framework 2.0 way to create a list  
List<int> list1 = new List<int>();  
 
// No boxing, no casting:  
list1.Add(8);  
 
// Compile-time error:  
// list1.Add("It is raining heavily outside."); 
// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();

// No boxing, no casting:
list1.Add(8);

// Compile-time error:
// list1.Add("It is raining heavily outside.");

对于客户端代码,与 ArrayList 相比,使用 List<T> 时添加的唯一语法是声明和实例化中的类型参数。虽然这稍微增加了些编码的复杂性,但好处是您可以创建一个比 ArrayList 更安全(由于指定了Type,所以可以进行编译时类型检查)并且速度更快(由于对于值类型无需进行装箱拆箱操作)的列表,特别适用于列表项是值类型的情况。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值