C# Where泛型约束规则

一.where 约束作用:

定义泛型的时候,我们可以使用 where 限制参数的范围
使用泛型的时候,你必须尊守 where 限制参数的范围,否则编译不会通过。

二.约束类型

  1. 类 约束
    类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型、字符串

        public static T[] ToNull<T>(this T[] arr) where T:class
        {
    	}
        T必须是 引用类型
    
  2. 结构体 约束
    类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。

        public static T[] ToNull<T>(this T[] arr) where T:struct
        {
    	}
        T必须是 值类型
    
  3. newI() 约束
    类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定

    class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new()
    {
    }
    
  4. <基类名> 约束
    类型参数必须是指定的基类或派生自指定的基类

    public class Employee{}
    
    public class GenericList<T> where T : Employee
    
  5. <接口名称> 约束
    类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的

    interface IMyInterface
    {
    }
    
    class Dictionary<TKey, TVal>
        where TKey : IComparable, IEnumerable
        where TVal : IMyInterface
    {
        public void Add(TKey key, TVal val)
        {
        }
    }
    
  6. U:T 约束
    U和T都是泛型 泛型U必须为T提供的参数或派生自为 U 提供的参数 也就是说T和U的参数必须一样

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

三.应用场景

  1. 可用于类:
    	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()
    
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值