where(泛型类型约束)

定义:在定义泛型的时候,咱们可使用 where 限制参数的范围。数组

使用:在使用泛型的时候,你必须尊守 where 限制参数的范围,不然编译不会经过。函数

 

六种类型的约束:spa

T:类(类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。)code

    class MyClass<T, U>
        where T : class///约束T参数必须为“引用 类型{ }”
        where U : struct///约束U参数必须为“值 类型”
    { }

T:结构(类型参数必须是值类型。能够指定除 Nullable 之外的任何值类型。)blog

    class MyClass<T, U>
        where T : class///约束T参数必须为“引用 类型{ }”
        where U : struct///约束U参数必须为“值 类型”
    { }

T:new()(类型参数必须具备无参数的公共构造函数。当与其余约束一块儿使用时,new() 约束必须最后指定。)继承

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

T:<基类名>(类型参数必须是指定的基类或派生自指定的基类。)接口

public class Employee{}

public class GenericList<T> where T : Employee

T:<接口名称>(类型参数必须是指定的接口或实现指定的接口。能够指定多个接口约束。约束接口也能够是泛型的。)文档

    /// <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)
        {
        }
    }

T:U(为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。也就是说T和U的参数必须同样it

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

 

1、可用于类:io

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

2、可用于方法:

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

3、可用于委托:

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

 

在实际项目中何时用到它们?

有时候你在作一个项目的时候,你须要用到泛型,你只但愿传给你的泛型参数是限定范围的,

好比你但愿值类型,或者是引用类型,或者是继承至某个类型、或者是符合某个接扣的类型,

这个时候你该如何办?你就须要用到 WHERE 来限定了。

 

参考文档:

https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx

https://msdn.microsoft.com/zh-cn/library/bb384067.aspx

相关文章
相关标签/搜索