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
    {

    }
相关推荐
灯澜忆梦9 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-9 小时前
C#中的StringBuilder相关方法
开发语言·c#
-银雾鸢尾-9 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
大模型码小白10 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
段一凡-华北理工大学12 小时前
向量数据库实战:选型、调优与落地~系列文章12:文本分块策略实战:chunk_size 怎么选?重叠多少?
开发语言·数据库·后端·oracle·rust·工业智能体·高炉智能化
Ljwuhe13 小时前
C++——多态
开发语言·c++
心平气和量大福大13 小时前
C#-WPF-Window主窗体
开发语言·c#·wpf
白露与泡影14 小时前
Arthas 实战指南:从方法耗时定位到 JVM 变量热修改
服务器·jvm·c#
从零开始的代码生活_15 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸15 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++