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>
    {...}
  • 相关阅读:
    dom4j解析xml字符串实例
    使用Dom4j生成xml文件(utf-8编码)
    viewer.js插件简单使用说明
    html标签title属性效果优化
    XML文件读写编码不是UTF-8的问题
    webservice wsdl文件标签讲解
    定销房概念扫盲
    Sql Server系列:视图
    Centos7安装mysql5.6
    java实现链式队列
  • 原文地址:https://www.cnblogs.com/entclark/p/8613506.html
Copyright © 2011-2022 走看看