// cs_where.cs // compile with: /target:library using System; class MyClassy<T, U> where T : class where U : struct ...{ }
where 子句还可以包括构造函数约束。可以使用 new 运算符创建类型参数的实例;但类型参数为此必须受构造函数约束 new() 的约束。new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数。例如:
// cs_where_3.cs // compile with: /target:library using System; using System.Collections; interface MyI ...{ } class Dictionary<TKey,TVal> where TKey: IComparable, IEnumerable where TVal: MyI ...{ publicvoid Add(TKey key, TVal val) ...{ } }
还可以将约束附加到泛型方法的类型参数,例如:
publicbool MyMethod<T>(T t) where T : IMyInterface ...{ }
在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。
// yield-example.cs using System; using System.Collections; publicclass List ...{ publicstatic IEnumerable Power(int number, int exponent) ...{ int counter =0; int result =1; while (counter++< exponent) ...{ result = result * number; yieldreturn result; } } staticvoid Main() ...{ // Display powers of 2 up to the exponent 8: foreach (int i in Power(2, 8)) ...{ Console.Write("{0} ", i); } } }