泛型约束

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