• 泛型约束


    一、使用where关键字限制类型参数

    泛型约束

    描述

    where T : struct

    类型参数<T>的继承链中必须有System.ValueType

    where T : class

    类型参数<T>的继承链中不允许有System.ValueType(例如<T>是一个引用类型)

    where T : new()

    类型参数<T>必须有一个默认构造函数。如果同时有多个限制,这个限制必须放在最后。

    where T : NameOfBaseClass

    类型参数<T>必须继承至基类NameOfBaseClass

    where T : NameOfInterface

    类型参数<T>必须实现接口NameOfInterface

    为了便于理解,下面通过几个例子来了解where的用法。虽然这都是太基础的东西,看到以前的笔记顺便copy过来了
    //T必须具备一个默认构造函数
    public class MyGenericClass<T> where T : new()
    {...}
    //T必须是一个具备默认构造函数的类,而且实现了IDrawable接口
    public class MyGenericClass<T> where T : class, IDrawable, new()
    {...}
    //MyGenericClass继承至MyBase类,实现了ISomeInterface接口;             
    //类型参数T的继承链中有System.ValueType
    public class MyGenericClass<T> : MyBase, ISomeInterface where T : struct
    {...}
    //类型参数K必须具备默认构造函数;类型参数T必须实现泛型接口IComparable<T>
    public class MyGenericClass<K, T> where K : new()
    where T : IComparable<T>
    {...}
  • 相关阅读:
    mongoTemplate.aggregate()聚合查询
    解决ElasticSearch5.x中@Field注解之IK分词不能用的问题
    Mybatis中使用Enum传参
    过滤,去重filter,去重reduce
    自己写的数组 方法的组合使用
    uni-app 使用vuex的方法
    uni-app实战写法
    vue的bug问题
    vuex
    vue webapp的基本功能实现方法
  • 原文地址:https://www.cnblogs.com/entclark/p/8613506.html
Copyright © 2020-2023  润新知