C# 泛型约束 xxx<T> Where T:约束(一)

泛型约束

代码举例

发现我们游戏的代码中,主程写了很多类似这样的代码:

public static T CreateObject<T>(out int objectId) where T : new() //方法名

//单例类
public class CSingleton<T> where T : new() 

//根据 url和Type 查找UI控件
public T GetControl<T>(string uri, Transform findTrans = null, bool isLog = true) where T : UnityEngine.Object 

public T FindControl<T>(string name) where T : Component

public void OpenWindow<T>(params object[] args) where T : CUIBase

public void CallUI<T>(Action<T, object[]> callback, params object[] args) where T : CUIBase

//加载Tab表
public void LoadTab<T>(string tabPath) where T : CBaseInfo, new()

具体使用

定义:public T GetInfo<T>(string id) where T : CBaseInfo

使用:ActorInfo actorInfo = CGameSettings.Instance.GetInfo<ActorInfo>(actorId);

解释:[T GetInfo(String id)]传入一个 ID 返回一个Class [where T:CBaseInfo]约束这个Class的Type 必须 继承之 CBaseInfo

插件也使用泛型写法

当然项目中使用一些插件也是有类似的写法

FingerGestures

public abstract class ContinuousGestureRecognizer<T> : GestureRecognizerTS<T> where T : ContinuousGesture, new()

public static T CreateAsset<T>() where T : ScriptableObject

public abstract class FingerEventDetector<T> : FingerEventDetector where T : FingerEvent, new()

NGUI

static public T[] FindActive<T> () where T : Component

static public T AddChild<T> (GameObject parent, bool undo) where T : Component

static public T Begin<T> (GameObject go, float duration) where T : UITweener

TK2D

public static T LoadResourceByName<T>(string guid) where T : UnityEngine.Object 

public static T AddComponent<T>(GameObject go, tk2dSpriteCollectionData spriteCollection, string spriteName) where T : tk2dBaseSprite
posted @ 2014-08-06 11:12  赵青青  阅读(24939)  评论(0编辑  收藏  举报