C#泛型类与结构
class C{} //合法
class D:C{} //合法
class E:C{} //合法
class F:C{} //合法
class G:C{} //非法
C#除可单独声明泛型类型(包括类与结构)外,也可在基类中包含泛型类型的声明。但基类如果是泛型类,他的类型参数要么已实例化,要么来源子类(同样是泛型类型)声明的类型参数。
泛型类型的成员
class C
{
public V f1; //声明字段
public D f2; //作为其他泛型类型 的参数
public C
{
this.f1 = x;
}
}泛型类型的成员可以使用泛型类型声明中的类型参数。但类型参数如果没有任何约束,则只能在该类型上使用从System.Object继承的共有成员。
泛型接口
interface IList
{
T[] GetElements();
}
interface IDictionary
{
void Add(K key,V value);
}
//泛型接口的类型参数要么已实例化
//要么来源于实现类声明的类型参数
class List:IList,IDictionary
{
public T[] GetElements{}
{
return null;
}
public void Add(int index,T value){}
}泛型委托
delegate bool Predicate(T value);
class X
{
static bool F(int i){...}
static bool G(string s){...}
static void Main()
{
Predicate p2 = G;
Predicate p1 = new Predicate(F);
}
}泛型委托支持返回值和参数哂纳感应用参数类型,这些参数类型同样可以附带合法的约束。