作用:泛型约束可以用来限制泛型类型参数的类型,以提供更多的类型安全性和灵活性
例子
下面是几种常见的泛型约束及其具体使用情况:
-
where T : class
:该约束要求泛型类型参数必须是引用类型。例如:public class MyClass<T> where T : class { // ... }
此时,
T
只能是引用类型(类、接口或委托),而不能是值类型。 -
where T : struct
:该约束要求泛型类型参数必须是值类型。例如:public class MyStruct<T> where T : struct { // ... }
此时,
T
只能是值类型(如int
、float
、struct
等),而不能是引用类型。 -
where T : new()
:该约束要求泛型类型参数必须具有无参构造函数。例如:public class MyGenericClass<T> where T : new() { public T CreateInstance() { return new T(); } }
这样,在使用该约束的泛型类或方法中,就可以通过
new T()
来创建T
类型的实例。 -
where T : <base class>
:该约束要求泛型类型参数必须是指定的基类或派生类。例如:public class MyGenericClass<T> where T : MyBaseClass { // ... }
此时,
T
必须是MyBaseClass
类型或其派生类。 -
where T : <interface>
:该约束要求泛型类型参数必须实现指定的接口。例如:public class MyGenericClass<T> where T : IMyInterface { // ... }
此时,
T
必须实现IMyInterface
接口。
使用泛型约束可以有效限制泛型类型参数的类型范围,提供编译时的类型安全和灵活性。通过添加适当的约束,可以在泛型代码中使用更具体的功能和特性。