首页 > 其他 > 详细

泛型约束

时间:2018-03-20 23:24:21      阅读:170      评论:0      收藏:0      [点我收藏+]

一、使用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>
{...}

 

泛型约束

原文:https://www.cnblogs.com/entclark/p/8613506.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!