zoukankan      html  css  js  c++  java
  • 泛型约束

    一、使用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>
    {...}
  • 相关阅读:
    Java 正则表达式的总结和一些小例子
    jquery用div模拟一个下拉列表框
    jquery点击div以外的区域触发事件
    Jackson 框架,轻易转换JSON
    Java Json API:Gson使用简单入门
    linux必学
    Python2 long() 函数
    Python int() 函数
    PyCharm快捷键大全
    PyCharm常用设置
  • 原文地址:https://www.cnblogs.com/entclark/p/8613506.html
Copyright © 2011-2022 走看看