泛型约束

泛型约束的概念

让泛型的类型有一定限制

值类型: where 泛型字母 : struct

引用类型: where 泛型字母 : class

存在无参公共构造函数: where 泛型字母 : new()

某个类本身或者其派生类: where 泛型字母 : 类名

某个接口的派生类型: where 泛型字母 : 接口名

另一个泛型类型本身或者其派生类型: where 泛型字母 : 另一个泛型字母


//值类型约束
class Test1<T> where T : struct
{
    public T value;
    public void TestFunc<K>(K k) where K : struct
    {

    }
}
//引用类型约束
class Test2<T> where T : class
{
    public T value;
    public void TestFunc<K>(K k) where K : class
    {

    }
}
//公共无参构造约束
//抽象函数不能使用
class Test3<T> where T : new()
{
    public T value;
    public void TestFunc<K>(K k) where K : new()
    {

    }
}
class TestClass
{

}
Test3<TestClass> t3 = new Test3<TestClass>();
//类约束
//必须是Test1或者Test1的子类
class Test4<T> where T : Test1
{
    public T value;
    public void TestFunc<K>(K k) where K : Test1
    {

    }
}
//接口约束
interface IFly
{

}
class Test5<T> where T : IFly
{
    public T value;
    public void TestFunc<K>(K k) where K : IFly
    {

    }
}
//另一个泛型约束
//T要不是U的本身类型,或者T是U的派生类型
class Test6<T,U> where T : U
{
    public T value;
    public void TestFunc<K,M>(K k) where K : M
    {

    }
}
//约束的组合使用
class Test6<T> where T : class,new()
{

}
//多个泛型有约束
class Test6<T,U> where T : class,new() where K:struct
{

}

复习
//索引器
public T this[int index]
{
    get
    {
        return array[index]
    }
    set
    {
        array[index] = value;
    }
}
posted @   cannedmint  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示