c#泛型约束

泛型约束概念

关键字 where

值类型 where T:struct

让泛型的类型有一定的限制

1值类型 where 泛型字母 struct

2引用类型 where 泛型字母 class

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

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

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

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

各泛型约束讲解

值类型约束

cs 复制代码
class Test1<T> where T:struct
{
    public T value;

    public void TestFun<K>(K v) where K:struct
    {
    }
}
   Test1<int> t1 = new Test1<int>();
   t1.TestFun<float>(1.3f);

引用类型约束

cs 复制代码
class Test2<T> where T:class
{
    public T value;
    public void TestFun<K>(K k) where K:class
    {
    }
}
Test2<Random> t2 = new Test2<Random>();
t2.value = new Random();
t2.TestFun<object>(new object());

公共无参构造约束

cs 复制代码
 class Test3<T> where T:new()
 {
     public T value;

     public void TestFun<K>(K k) where K : new()
     {

     }
 }
 class Test1
 {
     public Test1()
     {

     }
 }

 class Test2
 {
     public Test2(int a)
     {

     }
 }
Test3<Test1> t3 = new Test3<Test1>();

类约束

cs 复制代码
class Test4<T> where T : Test1
{
    public T value;

    public void TestFun<K>(K k) where K : Test1
    {

    }
}

class Test3:Test1
{

}
Test4<Test3> t4 = new Test4<Test3>();

接口约束

cs 复制代码
interface IFly
{

}

interface IMove:IFly
{

}

class Test4:IFly
{

}

class Test5<T> where T : IFly
{
    public T value;

    public void TestFun<K>(K k) where K : IFly
    {

    }
}
Test5<IMove> t5 = new Test5<IMove>();
t5.value = new Test4();

另一个泛型约束

类型参数 T 必须继承自另一个类型参数 U

cs 复制代码
class Test6<T,U> where T : U
{
    public T value;

    public void TestFun<K,V>(K k) where K : V
    {

    }
}
Test6<Test4, IFly> t6 = new Test6<Test4, IFly>();

约束的组合使用

cs 复制代码
class Test7<T> where T: class,new()
{

}

多个泛型有约束

cs 复制代码
    class Test8<T,K> where T:class,new() where K:struct
    {

    }
相关推荐
万物智能信息科技1 小时前
RK3568 的多路显示移植—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
linux·开发语言·华为·开源·harmonyos
蓝悦无人机2 小时前
Qt Design Studio(QDS)4.8.2项目文件结构详解
开发语言·qt·qt creator·qds·项目文件结构·qtc
yxlalm2 小时前
4.java秒杀项目第四课-后端商品后台接口
java·开发语言
孙启超2 小时前
【AI开发之Rust】第 1 课:认识 Rust 与开发环境 —— 装好工具链,跑通第一个程序
开发语言·人工智能·后端·ai·rust·安全架构
君顾12 小时前
家政派单小程序源码开发实战:从零搭建到上线全流程指南
java·开发语言·家政派单
1314lay_10073 小时前
C#调用Sql Server存储过程,有返回值的
数据库·sqlserver·c#
我是唐青枫3 小时前
C#.NET PInvoke 深入解析:封送、内存布局与原生互操作实战
开发语言·c#·.net
程序猿编码3 小时前
纯C++轻量计算机视觉推理引擎:基于GGML的端侧CV模型部署技术全解析
开发语言·c++·计算机视觉·大模型·transformer
Am-Chestnuts4 小时前
AI 生成的数学公式,怎么用 DS随心转 导出成 Word 里能改的公式
人工智能·c#·word
SEO_juper4 小时前
外贸多语言站最隐蔽的流量杀手:hreflang 错了,谷歌把德语页推给美国人(附审计脚本)
开发语言·前端·python·seo·独立站·谷歌优化