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


  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值