[C#复习向整合]泛型约束

概念:让泛型的类型有一定的限制

关键字where

语法where 泛型字母 : xxx

约束泛型是值类型                                        where T : struct

约束泛型是引用类型                                     where T : class

约束泛型要存在无参公共构造函数                where T : new()

约束泛型是某个类或其派生类                        where T : 类名

约束泛型是某个接口的派生类                        where T : 接口名

约束泛型是另一个泛型类型或派生类                where T : 另一个泛型字母

class Test1<T> where T : struct //泛型要是值类型
{
    public void TestFun<K>(K k) where K : struct//函数泛型要是值类型
    {
    
    }
}

class Test2<T> where T : class //泛型要是引用类型
{
    
}

class Test3<T> where T : new() //泛型要有公共无参构造(抽象类自然不行)
{

}


//一个自定义类
class TestClass
{

}
class Test4<T> where T : TestClass //或者是TestClass的子类
{
    
}

//一个测试接口
interface IFly
{

}
class TestClass2 : IFly
{

}
class Test5<T> where T : IFly //或者TestClass2
{

}

class Test6<T,U> where T : U
{
    //泛型T要么是U,要么是U的子类
}




约束的组合使用

class Test7<T> where T : class, new()
{
    //注意new()不能写在class前面!new()一般写在最后
}
//注意有些约束是不能搭配使用的,如struct 和 new()

多个泛型有约束

class Test8<T,K> where T : class where K : struc
{
     //where前不要加逗号
}

参考资料<唐老狮C#教程>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值