泛型介绍
2013-05-10 10:54 hduhans 阅读(190) 评论(0) 收藏 举报泛型是一种特殊的类型,允许程序员在强类型程序设计语言中编写代码时定义一些可变部分,那些部分在使用前必须作出指明。各种程序设计语言和其编译器、运行环境对泛型的支持均不一样。泛型类是引用类型,是堆对象,主要是引入了类型参数这个概念。
一、.NET Framework 的泛型
① 泛型类示例:
View Code
class Test<T> //泛型类 { public T obj; public Test(T obj) { this.obj = obj; } } class Program { static void Main(string[] args) { int obj = 2; Test<int> test = new Test<int>(obj); //如果泛型T被实例化为int型,那么成员变量obj就是int型的 Console.WriteLine("int:" + test.obj); string obj2 = "hello world"; Test<string> test1 = new Test<string>(obj2); //如果T被实例化为string型,那么obj就是string类型的。 Console.WriteLine("String:" + test1.obj); Console.Read(); } } //运行结果: //int:2 //StringLhello world
② 泛型方法:C#泛型机制只支持“在方法声明上包含类型参数”,例:
public static int FunctionName<T>(T value){/*方法体*/}
注:泛型方法的泛型定义应尽量避免与类泛型定义相同,编译器会报错,如
class A<T> { void p<T>() { } //T相同 编译器会报错 方法体的泛型T应与类的泛型T区分 如改写为U }
③ 泛型继承:若C#基类是泛型类,它的类型要么要么在继承时实例化,要么来源于继承它的子类。例:
View Code
class C<U,V> class D:C<string,int> class E<U,V>:C<U,V> class F<U,V>:C<string,int> class G:C<U,V> //非法 因为G类型不是泛型,C是泛型,G无法给C提供泛型的实例化
④ 泛型约束:C#共有四种泛型约束,分别是"基类约束","接口约束","构造器约束'和"值类型/引用类型约束",由where字句表达。
1) "基类约束"
View Code
class A { public void Func1() { } } class B { public void Func2() { } } class C<S, T> where S : A where T : B { public C(S s, T t) { s.Func1(); //S的变量可以调用Func1方法 t.Func2(); //T的变量可以调用Func2方法 } }
2) "接口约束"
View Code
interface IA<T> { T Func1(); } interface IB { void Func2(); } interface IC<T> { T Func3(); } class MyClass<T, V> where T : IA<T> where V : IB, IC<V> { public MyClass(T t, V v) { t.Func1(); //T的对象可以调用Func1 v.Func2(); //V的对象可以调用Func2和Func3 v.Func3(); } }
3) "构造器约束"(使用了构造器约束,就可以再类体内调用new T())
View Code
class A { public A() { } } class B { public B(int i) { } } class C<T> where T : new() { T t; public C() { t = new T(); } } class D { public void Func() { C<A> c = new C<A>(); //正确 C<B> d = new C<B>(); //报错 类B不支持无参数的构造函数 } }
4) "值类型/引用类型约束"
View Code
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是一个引用类型

浙公网安备 33010602011771号