泛型总结

mac2022-06-30  26

泛型

一、泛型体验

泛型是framework 2.0加入的一种特殊的算法重用机制,允许程序员在代码中将变量的类型先用类型占位符来替代,等到运行的时候在根据传入的类来替换。

Demo1

MyList类:

1 public class MyList<T> 2 { 3 T[] arr; 4 public int count=0; 5 public MyList(int length) 6 { 7 arr = new T[length]; 8 } 9 public void Add(T t) 10 { 11 arr[count] = t; 12 count++; 13 } 14 15 /// <summary> 16 /// 索引器 17 /// </summary> 18 /// <param name="index"></param> 19 /// <returns></returns> 20 public T this[int index] 21 { 22 get 23 { 24 if (index >= arr.Length) 25 { 26 throw new System.Exception("数组下标越界"); 27 } 28 else 29 { 30 return arr[index]; 31 } 32 } 33 set 34 { 35 if (index >= arr.Length) 36 { 37 throw new System.Exception("数组下标越界"); 38 } 39 else 40 { 41 arr[index]=value; 42 } 43 } 44 } 45 } View Code

调用:

1 protected void Page_Load(object sender, EventArgs e) 2 { 3 MyList<int> list = new MyList<int>(4); 4 5 list.Add(1); 6 list.Add(4); 7 list.Add(5); 8 list.Add(6); 9 for (int i = 0; i < list.count; i++) 10 { 11 Response.Write(list[i].ToString()); 12 } 13 } View Code

注意:

1、 是在运行时,将堆空间里的对象内部所有的占位符都替换成传入的类型.

2、 泛型是指带类型参数的类,而不是类型参数本身。

如:public class MyList<T>{..} 其实MyList就是泛型,而T是类型参数。

3、 clr编译时,编译器只为MyList<T>类型产生“泛型版”的IL代码------并不进行泛型的实例化,T在中间只充当占位符。

4、 执行的时候,当jit编译器第一次遇到MyList<int>时,将用int替代”泛型版”IL代码与源数据中的T------进行泛型类型的实例化。

5、 实例化一个引用类型的泛型,它在内存中分配的大小是一样的,实例化一个值类型的时候,在内存中分配的大小是不一样的,尽管如此,clr还是为每个不同的类型参数创建了不同的泛型类版本。

二、泛型类

1、多个类型参数用逗号隔开

  

2、泛型类的继承

     继承一个泛型类的时候,必须为父类传递泛型参数

     可以指定一个具体的参数类型:public class Son:Father<int,string>

     可以把子类的泛型参数赋值给父类泛型参数class Son<w,y>:Father<w,y>

三、泛型约束

构造器约束:Demo2

MyDog类:

1 public class MyDog<T> where T:new()//泛型约束,传进来的T类型必须有无参数的构造函数,不能约束是否有带参数的构造函数 2 { 3 T t; 4 public MyDog() 5 { 6 t = new T(); 7 } 8 } View Code

调用:

1 protected void Page_Load(object sender, EventArgs e) 2 { 3 MyDog<LittleDog> dog = new MyDog<LittleDog>(); 4 }

基类约束:用来约束泛型参数必须是某个类的子类,一个泛型参数不允许多少基类约束,不能为密封类指定基类约束(string)。

值类型约束:public class C<T> where T:struct

引用类型约束:public class C<T> where T:class

四、泛型方法

1、泛型方法的泛型参数,可以用在该方法的形参、方法体、返回值三处。

1 public K Test<k>(K a) where K:new() 2 3 { 4 5 K k1=new K(); 6 7 return k1; 8 9 }

2、泛型方法的重载

1 void SayB<T>{} 2 3 //void SayB<S>{}//和上面的实质一样,不构成重载 4 5 void SayB<T,T2>{} 6 7 void SayB<T>(string name) 8 9 //void SayB<T>(): where T:class //泛型类型约束不构成重载的条件

3、泛型方法的重写

1 public class Father 2 3 { 4 5 public virtual T Shout<T>() where T:new() 6 7 { 8 9 return new T(); 10 11 } 12 13 } 14 15 public class Son:Father 16 17 { 18 19 public override T Shout<t>()//在父类中设置了构造函数约束,子类中就不需要再约束了,T的名字即使不一样,也可以 20 21 { 22 return new T(); 23 24 } 25 26 } View Code

------------------------------------------------------------------------------------------------------------------------------------------

 软谋在线教育,最适合大学生、上班族的在线软件培训,主要教授asp.net动态网站制作,yy教育房间远程实时授课,每节课录制成高清视频课后分享,老师白天八小时全职在线辅导,不懂就问。加qq群:138800420 即可免费试听。

转载于:https://www.cnblogs.com/ruanmou001/p/3628747.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)