zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    ES5 05 Function扩展
    ES5 04 Array扩展
    ES5 03 Object扩展
    ES5 02 JSON对象
    ES5 01 严格模式
    Oracle 数据库复制
    PB函数大全
    Handle( ) //得到PB窗口型对象的句柄
    PB赋值粘贴 多个DW进行update
    pb 11 数据窗口空白,预览pb崩溃解决方案
  • 原文地址:https://www.cnblogs.com/xianyv/p/14849501.html
Copyright © 2011-2022 走看看