在C#中,用where
来约束泛型参数。能使用的大概有以下几种类型:
where T : struct
:泛型参数<T>
必须是值类型(struct
或者enum
)where T : class
:泛型参数<T>
必须是引用类型where T : new()
:泛型参数<T>
必须有默认构造函数。要注意的是如果有多个约束,这一个必须放在最后。where T : NameOfBaseClass
:泛型参数<T>
必须NameOfBaseClass
类的本身或者子类。where T : NameOfBaseInterface
:泛型参数<T>
必须实现了NameOfBaseInterface
接口。
具体可以看看下面的代码。
值类型和引用类型的约束:
C#
class MyClass<T, U>
where T : class
where U : struct
{ }
接口,默认构造函数的约束:
C#
public class MyGenericClass<T> where T : IComparable, new()
{
// The following line is not possible without new() constraint:
T item = new T();
}
多个约束
C#
interface IMyInterface:
{
}
class Dictionary<TKey, TVal>
where TKey : IComparable, IEnumerable
where TVal : IMyInterface
{
public void Add(TKey key, TVal val)
{
}
}