泛型类型参数的限制: where使用方法

设计泛型类:

利用泛型声明的类型限制机制,限制编译器类型参数的范围,运用 where 指令, 设置编译器限制范围,编译器就能在编译时刻对传入的类型进行检查。

    public class SortUtil<T> where T: ISortable    /// 泛型参数类型限制, 限制 T 为 ISortable 类型 
    {
        public  void   Sort(T target)
        {
            target.Sort();
        }
        public void SortDesc(T target)
        {
            target.SortDesc();
        }
    }

where 使用上的限制:

条件约束 说明
where T : struct

类型参数必须是实值类型

可以指定Nullable以外的任何实值类型

where T: class 类型参数必须是引用类型,指任何类(class)、接口(interface)、委托(delegate)或数组(array)类型
where T: new ()

类型参数必须拥有声明为public 的无参数构造函数

将new()条件约束与其他条件约束一起使用时,一定要将其指定为最后一个

where T: <base class name> 类型参数必须本身是指定的基类, 或派生自该类
where T: <interface name> 类型参数必须本身是指定的接口,或实现该接口可以同时指定多个接口条件约束限制的接口也可以是泛型的
where T: U 提供给T的类型参数必须是(或派生自)提供给U的参数

 

 

 

 

 

 

 

 

 

链接: where(泛型类型约束)

 

posted @ 2018-02-27 16:30  jason_LSZ  阅读(333)  评论(0编辑  收藏  举报