C#中的泛型约束
C#中的泛型约束只支持显示的约束,因为这样才能保证C#中的类型安全,但显示的约束并非是必须的,如果不加约束,泛型类型参数将只能访问System.object类型中的公有方法。“显示约束”由Where子句表达,可以指定“基类约束”、“接口约束”、“构造器约束”、“值类型/引用类型约束”
/************基类约束*****************/
class A
{
public void F1() { }
}
class B
{
public void F2() { }
}
class C<S, T>
where S : A //S继承自A
where T : B //T继承自B
{
//可以在类型为S的变量上调用F1,
//可以在类型为T的变量上调用F2
}
/***********接口约束********************/
interface IPrIntable
{
void PrInt();
}
interface IComparable<T> { int CompareTo(T v);}
interface IkeyProvider<T> { T GetKey();}
class Dictionary<K, V> where K:IComparable<K> where V: IPrIntable,IkeyProvider<K>
{
//可以在类型为K的变量上条用CompareTo,可以在类型为V的变量上调用PrInt和GetKey
}
/*************构造器约束************************/
class A { public A() { } }
class B { public B(int i) { } }
class C<T> where T:new()
{
//可以在其中使用 T t=new T();
}
C<A> c = new C<A>();//可以;A有无参数的构造函数
C<B> c = new C<B>();//不可以,B没有无参数的构造函数
/*************值/引用类型约束*********************/
public struct A { }
public class B { }
class C<T> where T : struct
{
//T在这里是一个值类型
}
C<A> c = new C<A>(); //可以,A是一个值类型
C<B> c = new C<B>();//不可以,B是一个引用类型