C# 泛型约束

2018-01-16 02:54 更新

C#泛型约束

默认情况下,类型参数可以用任何类型替换。

约束可以应用于类型参数,以需要更具体的类型参数。

这些是可能的约束:

where T : base-class // Base-class constraint 
where T : interface  // Interface constraint 
where T : class      // Reference-type constraint 
where T : struct     // Value-type constraint (excludes Nullable types) 
where T : new()      // Parameterless constructor constraint 
where U : T          // Naked type constraint 

例子

在下面的例子中,GenericClass <T,U>要求T从Main派生并实现Interface1,并且要求U提供一个无参数的构造函数:

class Main {} 
interface Interface1 {} 

class GenericClass<T,U> where T : Main, Interface1
where U : new() {
  ...
} 

注意

约束可以应用于在方法和类型定义中定义类型参数的任何位置。

基类约束指定type参数必须对特定类进行子类化。

接口约束指定type参数必须实现该接口。

以下代码显示了如何编写一个通用Max方法,该方法最多返回两个值。

我们可以使用在框架中定义的通用接口IComparable <T>:

public interface IComparable<T> // Simplified version of interface 
{
    int CompareTo (T other); 
} 

下面的代码使用IComparable接口作为约束,我们可以写一个Max方法如下:

static T Max <T> (T a, T b) where T : IComparable<T> {
    return a.CompareTo (b) > 0 ? a : b; 
} 

Max方法可以接受任何类型的实现IComparable <T>的参数:

int z = Max (5, 10); // 10 
string last = Max ("A", "B");

子类化泛型类型

泛型类可以像非类类一样子类化。

子类可以保持基类的类型参数打开,如下例所示:

class Stack<T> {...} 
class SpecialStack<T> : Stack<T> {...} 

或者子类可以使用具体类型关闭泛型类型参数:

class IntStack : Stack<int> {...} 

一个子类型还可以引入新的类型参数:

class List<T> {...} 
class KeyedList<T,TKey> : List<T> {...} 
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号