泛型方法

SomeClass

  1. public class SomeClass
  2. {
  3. //这是一个通用方法。注意通用类型“T”。
  4. //该“T”将在运行时替换为实际类型。
  5. public T GenericMethod<T>(T param)
  6. {
  7. return param;
  8. }
  9. }

SomeOtherClass

  1. public class SomeOtherClass : MonoBehaviour
  2. {
  3. void Start ()
  4. {
  5. SomeClass myClass = new SomeClass();
  6. //为了使用此方法,必须告诉此方法用什么类型替换“T”。
  7. myClass.GenericMethod<int>(5);
  8. }
  9. }

泛型类

GenericClass

  1. //这是一个通用类。注意通用类型“T”。
  2. //“T”将被替换为实际类型,同样,
  3. //该类中使用的“T”类型实例也将被替换。
  4. public class GenericClass <T>
  5. {
  6. T item;
  7. public void UpdateItem(T newItem)
  8. {
  9. item = newItem;
  10. }
  11. }

GenericClassExample

  1. public class GenericClassExample : MonoBehaviour
  2. {
  3. void Start ()
  4. {
  5. //为了创建通用类的对象,必须指定希望该类具有的类型。
  6. GenericClass<int> myClass = new GenericClass<int>();
  7. myClass.UpdateItem(5);
  8. }
  9. }

泛型约束

where关键字
在定义泛型时,可以对客户端实例化类时对于类型参数(泛型)的类型种类施加限制

  • T:<基类名> 必须是指定的基类或派生自指定的基类
  • T:<接口> 必须是指定的接口或实现了指定的接口
  • T:struct 类型参数必须为值类型
  • T:class 类型参数必须为引用类型(类、接口、委托)
  • T:new( ) 类型参数必须有无参数的公共构造函数
    1. //where T : IComparerable<T> 表示T类型实现了IComparable接口
    2. public class Comparer<T> where T : IComparable<T>
    3. {
    4. public T comparerTwoData(T a,T b)
    5. {
    6. if(a.CompareTo(b)>0)
    7. {
    8. return a;
    9. }
    10. else return b;
    11. }
    12. }
    1. using System; //这允许 IComparable 接口
    2. public class Student:IComparable<Student>
    3. {
    4. public int age;
    5. public string name;
    6. //接口实现
    7. public int CompareTo(Studnet other)
    8. {
    9. return this.age.CompareTo(other.age);
    10. }
    11. }

    主调类

    1. Student stu01 = new Student(){age=12,name="01"};
    2. Student stu02 = new Student(){age=16,name="02"};
    3. Compare<Student> com=new Compare<Student>();
    4. com.comparerTwoData(stu01,stu02);