C # class method declaration where _ gift of zookeeper,

Source: Internet
Author: User

C # class method declaration where _ gift of zookeeper,
The where clause is used to specify type constraints. These constraints can be used as variables for type parameters defined in generic declarations.
1. Interface constraints.
For example, you can declare a generic class.MyGenericClassIn this way, the type parameterTYou can implement the IComparable <T> interface:

Public class MyGenericClass <T> where T: IComparable {}
2. base class constraints: indicates that a type must use the specified class as the base class (or the class itself) to be used as the type parameter of the generic type.
This constraint must appear before all other constraints of this type of parameter.
Class MyClassy <T, U>
Where T: class
Where U: struct
{
}
3. The where clause can also include constructor constraints.
You can use the new operator to create an instance of the type parameter. However, the type parameter must be subject to the constructor constraints of new. The new () constraint allows the compiler to know that any type of parameter provided must have an accessible, non-parameter (or default) constructor. For example:
Public class MyGenericClass <T> where T: IComparable, new ()
{
// The following line is not possible without new () constraint:
T item = new T ();
}
The new () constraint appears at the end of the where clause.

4. For Multiple type parameters, each type parameter 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)
{
}
}

5. You can also attach constraints to type parameters of generic methods, for example:

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

Note that for delegates and methods, the syntax for describing type parameter constraints is the same:

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.