泛型是什么?
这是摘自百度百科中对泛型的介绍:
泛型是c#2.0的一个新增加的特性,它为使用c#语言编写面向对象程序增加了极大的效力和灵活性。不会强行对值类型进行装箱和拆箱,或对引用类型进行向下强制类型转换,所以性能得到提高。通过知道使用泛型定义的变量的类型限制,编译器可以在一个高得多的程度上验证类型假设,所以泛型提高了程序的类型安全。它允许程序员将一个实际的数据类型的规约延迟至泛型的实例被创建时才确定。泛型为开发者提供了一种高性能的编程方式,能够提高代码的重用性,并允许开发者编写非常优雅的解决方案。
|
看过之后,会用的还是懂;不会用的,也还是不懂。
一:泛型方法
所以我们还是看看泛型具体在程序中的应用:
//泛型方法 //unity3D中用的最多的泛型方法应该是GetCompent<T> //T就是占位符,当调用这个方法的你要告诉编译器,这个T的具体类型。 //另外,"T"只是一个标识,完全可以用其他代替,如"K","MyType"等,只是使用习惯。 //比如: GameObject player; Animator animator; void Start() { //在场景中找到名为MyPlayer物体 player = GameObject.Find("MyPlayer"); //获取该物体上的Animator组件 animator = player.GetComponent<Animator>(); //对于使用AddComponent<T>()、GetCompent<T>()这两个泛型方法来说,需要了解的就是:T就是你想要的具体的组件类型。 //对于泛型方法来说,泛型的作用就是占位和约束的作用。 } //下面来说声明泛型函数 /// <summary> /// 比较等级; /// </summary> /// <returns> /// 若t1>=t2的等级,则返回true;否则返回false /// </returns> /// where T : IRole where K : IRole的作用是约束传入的两个参数类型必须要实现IRole这个接口; /// 这样就定义好了一个泛型方法 public bool CompareLevel<T,K>(T t1, K t2) where T : IRole where K : IRole { //因为泛型t1,t2都被约束需要实现接口,所以我们可以强制转换到IRole来获取level比较 return ((IRole)t1).level >= ((IRole)t2).level; } //那么怎么使用呢? //接下来看: public void Test() { //先定义三个测试用的类型 MyNPC npc =new MyNPC(); MyPlayer player =new MyPlayer(); MyMonster monster =new MyMonster(); //对各个类型的level赋值 npc.level =1; player.level =2; monster.level =3; //比较npc和player的level就很简单了,只需要这样调用即可 bool b1 = CompareLevel<MyNPC,MyPlayer>(npc,player); //npc?payer//false bool b2 = CompareLevel<MyNPC,MyMonster>(npc,monster);//npc?monster//false bool b3 = CompareLevel<MyPlayer,MyMonster>(player,monster);//payer?monster//false } public interface IRole { int level{get;set;} } public class MyPlayer:IRole { public int level{get;set;} } public class MyNPC:IRole { public int level{get;set;} } public class MyMonster:IRole { public int level{get;set;} }
二:泛型类
最典型的例子就是List:
List<T>类是 ArrayList 类的泛型等效类。 该类使用大小可按需动态增加的数组实现 IList<T> 泛型接口。
List<T> mList = new List<T>();
示例代码如下:
接下来是泛型的继承:
三:泛型接口
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace 泛型
- {
- class 泛型接口
- {
- public static void Main()
- {
- PersonManager man = new PersonManager();
- Person per = new Person();
- man.PrintYourName(per);
- Person p1 = new Person();
- p1.Name = "p1";
- Person p2 = new Person();
- p2.Name = "p2";
- man.SwapPerson<Person>(ref p1, ref p2);
- Console.WriteLine( "P1 is {0} , P2 is {1}" , p1.Name ,p2.Name);
- Console.ReadLine();
- }
- }
- //泛型接口
- interface IPerson<T>
- {
- void PrintYourName( T t);
- }
- class Person
- {
- public string Name = "aladdin";
- }
- class PersonManager : IPerson<Person>
- {
- #region IPerson<Person> 成员
- public void PrintYourName( Person t )
- {
- Console.WriteLine( "My Name Is {0}!" , t.Name );
- }
- #endregion
- //交换两个人,哈哈。。这世道。。
- //泛型方法T类型作用于参数和方法体内
- public void SwapPerson<T>( ref T p1 , ref T p2)
- {
- T temp = default(T) ;
- temp = p1;
- p1 = p2;
- p2 = temp;
- }
- }
- }