where(C#参考)

  现在看到许多泛型类后面都会加上where关键字,一直都没去弄明白,今天有时间看了下,where子句用于指定类型约束,这些约束可以作为泛型声明中定义的类型参数的变量。

  例如,可以声明一个泛型类 MyGenericClass,这样,类型参数 T 就可以实现 IComparable<T> 接口:

public   class  MyGenericClass < T >   where  T:IComparable { }

 

  除了接口约束,where 子句还可以包括基类约束,以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。

 1  //  cs_where.cs
 2  //  compile with: /target:library
 3  using  System;
 4 
 5  class  MyClassy < T, U >
 6       where  T :  class
 7       where  U :  struct
 8  { }

 

  where 子句还可以包括构造函数约束。可以使用 new 运算符创建类型参数的实例;但类型参数为此必须受构造函数约束 new() 的约束。new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数。例如:

ExpandedBlockStart.gif 代码
1  //  cs_where_2.cs
2  //  compile with: /target:library
3  using  System;
4  public   class  MyGenericClass  < T >   where  T: IComparable,  new ()
5  {
6       //  The following line is not possible without new() constraint:
7      T item  =   new  T();
8  }

  new() 约束出现在 where 子句的最后。

  对于多个类型参数,每个类型参数都使用一个 where 子句,例如:

ExpandedBlockStart.gif 代码
 1  //  cs_where_3.cs
 2  //  compile with: /target:library
 3  using  System;
 4  using  System.Collections;
 5 
 6  interface  MyI
 7  {
 8  }
 9 
10  class  Dictionary < TKey,TVal >
11       where  TKey: IComparable, IEnumerable
12       where  TVal: MyI
13  {
14       public   void  Add(TKey key, TVal val)
15      {
16      }
17  }

 

  还可以将约束附加到泛型方法的类型参数,例如:

public   bool  MyMethod < T > (T t)  where  T : IMyInterface { }

  请注意,对于委托和方法两者来说,描述类型参数约束的语法是一样的:

delegate  T MyDelegate < T > ()  where  T :  new ()

 

  以上基本上是转载,希望各位看客原谅。

转载于:https://www.cnblogs.com/549504182/archive/2010/05/25/1743287.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值