.NET支持的类型参数约束有以下五种:
where T : struct | T必须是一个结构类型
where T : class | T必须是一个Class类型
where T : new() | T必须要有一个无参构造函数
where T : NameOfBaseClass | T必须继承名为NameOfBaseClass的类
where T : NameOfInterface | T必须实现名为NameOfInterface的接口
下面是泛型约束的实例:
using UnityEngine;
using System.Collections;
public class WhereT : MonoBehaviour {
public class Test2
{
public Test2()
{
}
}
public class Test1
{
}
public class GenericClass<T>
{
public void DoSomething(T t)
{
Debug.Log ("Type : " + t);
}
}
public class A<T>where T : class
{
public void DoSomething(T t)
{
Debug.Log ("Type : " + t.ToString());
}
}
public class B<T> where T : new ()
{
public void DoSomething(T t)
{
Debug.Log ("Type : " + t);
}
}
public class C<T> where T : class, new ()
{
public void DoSomething(T t)
{
Debug.Log ("Type : " + t);
}
}
// Use this for initialization
void Start () {
Example4 ();
}
void Example4()
{
Test1 t1 = new Test1();
C<Test1> c1 = new C<Test1> ();
c1.DoSomething (t1);
Test2 t2 = new Test2();
C<Test2> c2 = new C<Test2> ();
c2.DoSomething (t2);
}
void Example3()
{
Test2 t = new Test2();
B<Test2> b = new B<Test2> ();
b.DoSomething (t);
}
void Example2()
{
Test1 t = new Test1();
A<Test1> a = new A<Test1> ();
a.DoSomething (t);
}
void Example1()
{
int i = 0;
GenericClass<int> gci = new GenericClass<int> ();
gci.DoSomething (i);
string s = "hello";
GenericClass<string> gcs = new GenericClass<string> ();
gcs.DoSomething (s);
}
// Update is called once per frame
void Update () {
}
}