C # where usage

C # where clause
 
where clause specifies the type of constraints, which can be used as a variable parameter of the type defined in the generic declaration.
 1. interface constraints.
 For example, a generic class declaration  MyGenericClass , this type parameter  T  can be achieved IComparable <T> Interface:

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

 2. The base class constraint: Indicates a type must be specified class as a base class (or just the class itself) , it can be used as the generic type parameter type.
 Such constraints once used, must appear before all other constraints of the type parameter.
class MyClassy<T, U>
 where T :  class
 where U :  struct
{
}

 3.where clause may further comprise constructor constraint.
 Can create an instance of type parameters using the new operator; however, this must be constrained type parameter constructor constraint new () is. new () constraint allows the compiler to know: any type of parameters provide must have no parameters accessible (or default) constructor. E.g:
public class MyGenericClass <T> where T: IComparable, new ()
{
 // The following line is not possible without new() constraint:

 T item = new  T();
}
new () constraint appear in the final where clause.

 4. For a plurality of types of parameters, each parameter type uses a where clause,
 for example:
interface  MyI { }
class Dictionary<TKey,TVal>

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

The parameter type may also be attached to the constraint of a generic method, for example:

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

Note that for both the commission and methods for describing the type parameter constraint syntax is the same:

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

 Link from : http://hi.baidu.com/%D0%A6%D3%F0%BA%A8%CC%EC/blog/item/9701871c28d2fb13413417fd.html

转载于:https://www.cnblogs.com/zhangchenliang/archive/2012/01/09/2316985.html

Guess you like

Origin blog.csdn.net/weixin_34302561/article/details/93494977