在C#中,where
关键字用于泛型中的约束,以便限制泛型参数 T
可以是哪些类型。以下是 where
约束的几种类型:
类类型约束(Class Constraint):
指定
T
必须是引用类型。使用
where T : class
表示。
结构体约束(Struct Constraint)或 值类型约束(ValueType Constraint):
指定
T
必须是值类型。使用
where T : struct
表示。通常与
notnull
约束结合使用,以确保值类型不是null
。
接口约束(Interface Constraint):
指定
T
必须实现一个或多个接口。使用
where T : IInterface
表示,可以指定多个接口,用逗号分隔。
基类约束(Base Type Constraint):
指定
T
必须是指定类的子类或本身。使用
where T : BaseClass
表示。
构造函数约束(Constructor Constraint):
指定
T
必须有一个公开的无参数构造函数。使用
where T : new()
表示。必须写在最后面
多重约束(Multiple Constraints):
可以同时使用多个约束来进一步限制
T
。使用
where T : class, IInterface1, IInterface2
表示。
类型参数约束(Type Parameter Constraint):
从C# 7.1开始,可以使用特定的类型作为约束,要求
T
是给定类型的子类或实现给定接口。使用
where T : SomeType
表示。
null 约束(Null Constraint):
从C# 8.0开始,可以指定引用类型参数可以为
null
。使用
where T : class?
表示T
可以是null
。
引用类型:数组、类、接口、委托、object、字符串
值类型:结构体类型struct/int,double ,bool,枚举