泛型约束
(1)引用类型约束:泛型必须是引用类型
public class AGenericClass<T> where T : class{……}
(2)值类型约束:泛型必须是值类型
public class AGenericClass<T> where T : struct{……}
(3)new约束:泛型必须包含无参构造方法(如与其他约束共用,则放在最后)
public class AGenericClass<T> where T : new(){……}
(4)类名约束:泛型必须是某类或派生自某类(与接口共用,则放在接口前方)
public class AGenericClass<T> where T : Person{……}
(5)接口约束:泛型必须实现一个或多个接口
public class AGenericClass<T> where T : IOne,ITwo,IThree{……}
(6)多泛型约束:有多个泛型
public class AGenericClass<T,B> where T : IOne where B: class{……}
泛型继承
拥有泛型约束的类作为父类,则其子类可以选择特化父类,或者使用与父类同样/更严格的约束
class MyClass{……}
↓
class MyClassSon:MyClass{……}
public class AGenericClass<T> where T : MyClass
特化父类
public class MyTest : AGenericClass<MyClass>{……}
public class MyTest : AGenericClass<MyClassSon>{……}
使用与父类同样的约束
public class MyTest<B> : AGenericClass<B> where B:MyClass
使用比父类更严格的约束
public class MyTest<B> : AGenericClass<B> where B:MyClass,IOne
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Csharp泛型
{
class Csharp泛型继承
{
}
public class class1
{
}
public class class1son : class1
{
}
public class class2<T> where T: class1
{
public T a;
}
//特化父类
public class class3 : class2<class1>
{
}
//特化父类
public class class4 : class2<class1son>
{
}
//与父类相同约束
public class class5<T> : class2<T> where T:class1
{
}
//使用比父类更严格的约束
public class class6<T>:class2<T> where T : class1,IAttack
{
}
public interface IAttack
{
}
}
b站up视频链接(讲得很好):
【90 C#教程-泛型约束】 https://www.bilibili.com/video/BV1kP41197YV/?share_source=copy_web&vd_source=e09d10a3f6f91f4e730a7043a0df97a0