知识回顾
//泛型类
class TestClass<T, U>
{
public T t;
public U u;
public U TestFun(T t)
{
return default(U);
}
//泛型函数
public V TestFun<K, V>(K k)
{
return default(V);
}
}
什么是泛型约束
让泛型的类型有一定的限制
关键字:where
泛型约束一共有6种
值类型 | where 泛型字母:struct |
引用类型 | where 泛型字母:class |
存在无参公共构造函数 | where 泛型字母:new() |
某个类本身或者其派生类 | where 泛型字母:类名 |
某个接口的派生类型 | where 泛型字母:接口名 |
另一个泛型类型本身或者派生类型 | where 泛型字母:另一个泛型字母 |
where 泛型字母:(约束的类型)
各泛型约束讲解
值类型约束
class Test1<T> where T:struct
{
public T value;
public void TestFun<K>(K v) where K:struct
{
}
}
引用类型约束
class Test2<T> where T:class
{
public T value;
public void TestFun<K>(K k) where K:class
{
}
}
公共无参构造函数
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)
{
}
}
类约束
class Test4<T> where T : Test1
{
public T value;
public void TestFun<K>(K k) where K : Test1
{
}
}
class Test3:Test1
{
}
接口约束
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
{
}
}
另一个泛型约束
class Test6<T,U> where T : U
{
public T value;
public void TestFun<K,V>(K k) where K : V
{
}
}
约束的组合使用
class Test7<T> where T: class,new()
{
}
多个泛型有约束
class Test8<T,K> where T:class,new() where K:struct
{
}
总结
泛型约束:让类型有一定限制
class
struct
new()
类名
接口名
另一个泛型字母
注意:
1.可以组合使用
2.多个泛型约束 用where连接即可