C# 关键字 where 泛型约束

**泛型约束:**顾名思义,用以约束范型。
带佬文章:C# 泛型方法Where 约束-----foreverhot1019

我在此就写一下自己code出来的一些案例,用于记忆,如若有错,请联系我进行更正。
带佬文章写有六种约束,我暂且不这样记,我以自己的方法记忆,where就是一种约束,至于怎么约束再具体看。
首先约束的 样子是 where T : ____

+ keyword

where T : class 必须是引用类型

   class test_limit_class<T> where T : class
    {
        public T t;
    }
   class program
   {
      void main()
      {
         test_limit_class<int> limitc1 = new test_limit_class<int>();🙅🏻🙅🏻🙅🏻
      }
   }

泛型 T 被关键字 class 约束,此处在 main 函数中我们定义的 Tint 型,故此处会报错。

where T : struct T必须是值类型

where T : new() T必须有无参构造函数(此处只针对类)

1.类一个构造函数都没有,成立。
2.类存在有参构造函数时,则必须存在无参构造函数才能成立。
3.结构体一直成立。

+ baseclass

where T : baseclass T必须派生自baseclass

此处我测试了一下基类型,应该是可以以baseclass为起点,然后后面派生类包括baseclass都行。
例如 Human=>Man=>boy :

class test<T> where T:Human{}
test<Human> t1 = new test<Human>();👌🏻👌🏻👌🏻
test<Man> t2 = new test<Man>();👌🏻👌🏻👌🏻
test<boy> t3 = new test<boy>();👌🏻👌🏻👌🏻

+ interface

//interface declaration
interface IMyinterface{ void func();}
//the class which realize interface
class A : IMyinterface()
{
   void func()
   {}
}
//Generic limit
class test<T> where T:IMyinterface{}
//declaration and init
test<A> a = new test<A>();👌🏻👌🏻👌🏻

T 类型必须实现该接口

where T :U

带佬说 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。也就是说T和U的参数必须一样
此处我SB的测了个class和struct,虽然属性一样,但是会报错,因为不是派生关系。
带佬说的T提供的参数要和U提供的参数一样,此处我写了个非派生关系,但字段一样的两个类,但是还是会报错,结构体也是一样的。
在这里插入图片描述
在这里插入图片描述
error! 好像得派生才能suitable。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值