c # where (generic type constraint)

Original: c # the WHERE (generic type constraint)

Definitions: In the definition of generics , we can use  where  limiting parameter range.

Use: The use of generics time, you have to respect the  where  limiting parameters of range, or the compiler will not pass.

 

Six types of constraints:

T: class (type parameter must be a reference type; this also applies to any classes, interfaces, delegates, or array type.)

    MyClass class <T, U> 
        WHERE T: class parameter T /// constraint must "reference type {}" 
        WHERE U: U struct /// constraint parameter must be "value type" 
    {}

T: Structure (must be a value type parameter can specify the type Nullable any value other than the type.)

    MyClass class <T, U> 
        WHERE T: class parameter T /// constraint must "reference type {}" 
        WHERE U: U struct /// constraint parameter must be "value type" 
    {}

T: new new () (type parameter must have free public constructor parameters when used in conjunction with other constraints, new () constraint must be specified last.)

class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new()
{
    // ...
}

T: <base class name> (type parameter must be specified in the base class or derived from the base class specified.)

public class Employee{}

public class GenericList<T> where T : Employee

T: <interface name> (Type parameter must be specified interface or implement the specified interface can specify multiple interfaces may be the constraining the interface is generic.)

Copy the code
    /// <summary>
    /// 接口
    /// </summary>
    interface IMyInterface
    {
    }

    /// <summary>
    /// 定义的一个字典类型
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TVal"></typeparam>
    class Dictionary<TKey, TVal>
        where TKey : IComparable, IEnumerable
        where TVal : IMyInterface
    {
        public void Add(TKey key, TVal val)
        {
        }
    }
Copy the code

T: U (. Parameter type parameter T must be provided for the U-supplied or derived from parameters provided for the U That T and U parameters must be the same )

class List<T>
{
    void Add<U>(List<U> items) where U : T {/*...*/}
}

 

First, the class can be used:

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

Second, the method may be used:

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

Third, the commission can be used to:

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

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11286115.html