C# 泛型约束/类型参数的约束

约束指定类型参数的功能和预期。 声明这些约束意味着你可以使用约束类型的操作和方法调用。

通过使用 where 上下文关键字指定约束

 下表列出了各种类型的约束:

约束 描述
where T : struct 类型参数必须是不可为 null 的值类型。
where T : class 类型参数必须是引用类型。 
where T : class? 类型参数必须是可为 null 或不可为 null 的引用类型。
where T : notnull 类型参数必须是不可为 null 的类型。
where T : default 重写方法或提供显式接口实现时,如果需要指定不受约束的类型参数,此约束可解决歧义。
where T : unmanaged 类型参数必须是不可为 null 的非托管类型。
where T : new() 类型参数必须具有公共无参数构造函数。

where T: <base class name>

类型参数必须是指定的基类或派生自指定的基类。 
 where T : <base class name>? 类型参数必须是指定的基类或派生自指定的基类。 在 C# 8.0 及更高版本中的可为 null 上下文中,T 可以是从指定基类派生的可为 null 或不可为 null 的类型。
where T : <interface name> 类型参数必须是指定的接口或实现指定的接口。 可指定多个接口约束。 约束接口也可以是泛型。
where T : <interface name>? 类型参数必须是指定的接口或实现指定的接口。 可指定多个接口约束。 约束接口也可以是泛型。
where T : U 为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。

示例:

class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new()
{
    // ...
}

 

资料参考:

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#why-use-constraints

posted on 2021-06-04 14:40  进击の咸鱼  阅读(313)  评论(0编辑  收藏  举报

导航