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
    {

    }
相关推荐
Logintern093 分钟前
装饰器和洋葱模式的区分
开发语言·python·架构
冻柠檬飞冰走茶18 分钟前
《数据结构实验指导-C++语言版》 在顺序表 list 中查找元素 x
开发语言·数据结构·c++·算法·list
Brilliantwxx18 分钟前
【C++】 高阶数据结构图(1)并查集
开发语言·数据结构·c++
lancyu19 分钟前
# Agent Loop:AI Agent 的唯一直心骨
开发语言·javascript·人工智能
frjc1 小时前
阿里云 ACK 环境 Arthas 在线调试指南
开发语言·python
longxiaozhang62 小时前
C#继承:让代码少写一点,偷懒的好方法
开发语言·c#
weixin_440730502 小时前
python+request实现接口-参数化小结
开发语言·python
CHHH_HHH2 小时前
【Linux系统篇】深入解析Linux文件系统:从磁盘寻址到软硬链接
linux·服务器·开发语言·后端·ubuntu
yngsqq2 小时前
窗体快速取消
java·开发语言
rockey6272 小时前
C#脚本引擎之AScript与DynamicExpresso对比
c#·.net·script·动态脚本