**泛型约束:**顾名思义,用以约束范型。
带佬文章: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 函数中我们定义的 T 为 int 型,故此处会报错。
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。