泛型約束
代碼舉例
發現我們游戲的代碼中,主程寫了很多類似這樣的代碼:
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