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
    {

    }
相关推荐
雨落倾城夏未凉3 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫4 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫5 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6255 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902115 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠6 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫8 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech9 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf10 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m62510 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#