1. 程式人生 > >where T : class 泛型約束

where T : class 泛型約束

.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 () {
	
	}
}