概念:让泛型的类型有一定的限制
关键字where
语法where 泛型字母 : xxx
约束泛型是值类型 where T : struct
约束泛型是引用类型 where T : class
约束泛型要存在无参公共构造函数 where T : new()
约束泛型是某个类或其派生类 where T : 类名
约束泛型是某个接口的派生类 where T : 接口名
约束泛型是另一个泛型类型或派生类 where T : 另一个泛型字母
class Test1<T> where T : struct //泛型要是值类型
{
public void TestFun<K>(K k) where K : struct//函数泛型要是值类型
{
}
}
class Test2<T> where T : class //泛型要是引用类型
{
}
class Test3<T> where T : new() //泛型要有公共无参构造(抽象类自然不行)
{
}
//一个自定义类
class TestClass
{
}
class Test4<T> where T : TestClass //或者是TestClass的子类
{
}
//一个测试接口
interface IFly
{
}
class TestClass2 : IFly
{
}
class Test5<T> where T : IFly //或者TestClass2
{
}
class Test6<T,U> where T : U
{
//泛型T要么是U,要么是U的子类
}
约束的组合使用
class Test7<T> where T : class, new()
{
//注意new()不能写在class前面!new()一般写在最后
}
//注意有些约束是不能搭配使用的,如struct 和 new()
多个泛型有约束
class Test8<T,K> where T : class where K : struc
{
//where前不要加逗号
}
参考资料<唐老狮C#教程>