C#中的where从句

C#中的where从句

2011-07-03 13:07OrphousV 分类:C#/.NET | 浏览8443次
能解释一下下面两段代码中where的作用吗?
using System;
public class MyGenericClass <T> where T: IComparable, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}

using System;
using System.Collections;

interface MyI
{
}

class Dictionary<TKey,TVal>
where TKey: IComparable, IEnumerable
where TVal: MyI
{
public void Add(TKey key, TVal val)
{
}
}

另外,这个特性具体有什么实际意义?怎么应用?希望举一个例子。
 
泛型类定义时的where子句表示的是泛型类型约束,也就是对泛型需要满足的条件的一个限制。
比如
where T: IComparable, new()
说明,这里的泛型T必须实现IComparable接口,并且必须有公有无参数构造函数。
因为泛型为中可能会用到一些与泛型相关的操作,但因为是泛型,所以不能保证使用时的泛型一定能进行这项操作,所以有这么个约束,保证在程序编译时能够检查出泛型是否满足要求。
例如,你写的MyGenericClass类中,对T进行了实例化:new T(),这就要求T一定要有公有无参数构造函数,如果没有where中的泛型类型约束,是不能保证这样实例化能够成功的。
更详细的说明,可以参考:

posted on 2015-05-07 17:22  chengjunde  阅读(398)  评论(0编辑  收藏  举报

导航