泛型方法
SomeClass
public class SomeClass
{
//这是一个通用方法。注意通用类型“T”。
//该“T”将在运行时替换为实际类型。
public T GenericMethod<T>(T param)
{
return param;
}
}
SomeOtherClass
public class SomeOtherClass : MonoBehaviour
{
void Start ()
{
SomeClass myClass = new SomeClass();
//为了使用此方法,必须告诉此方法用什么类型替换“T”。
myClass.GenericMethod<int>(5);
}
}
泛型类
GenericClass
//这是一个通用类。注意通用类型“T”。
//“T”将被替换为实际类型,同样,
//该类中使用的“T”类型实例也将被替换。
public class GenericClass <T>
{
T item;
public void UpdateItem(T newItem)
{
item = newItem;
}
}
GenericClassExample
public class GenericClassExample : MonoBehaviour
{
void Start ()
{
//为了创建通用类的对象,必须指定希望该类具有的类型。
GenericClass<int> myClass = new GenericClass<int>();
myClass.UpdateItem(5);
}
}
泛型约束
where关键字
在定义泛型时,可以对客户端实例化类时对于类型参数(泛型)的类型种类施加限制
- T:<基类名> 必须是指定的基类或派生自指定的基类
- T:<接口> 必须是指定的接口或实现了指定的接口
- T:struct 类型参数必须为值类型
- T:class 类型参数必须为引用类型(类、接口、委托)
- T:new( ) 类型参数必须有无参数的公共构造函数
//where T : IComparerable<T> 表示T类型实现了IComparable接口
public class Comparer<T> where T : IComparable<T>
{
public T comparerTwoData(T a,T b)
{
if(a.CompareTo(b)>0)
{
return a;
}
else return b;
}
}
using System; //这允许 IComparable 接口
public class Student:IComparable<Student>
{
public int age;
public string name;
//接口实现
public int CompareTo(Studnet other)
{
return this.age.CompareTo(other.age);
}
}
主调类
Student stu01 = new Student(){age=12,name="01"};
Student stu02 = new Student(){age=16,name="02"};
Compare<Student> com=new Compare<Student>();
com.comparerTwoData(stu01,stu02);