public class FFFTestView : MonoBehaviour { // Use this for initialization void Start () { TestManage.instance.load("AA"); TestManage.instance.load("BB"); TestManage.instance.load("CC"); TestManage.instance.load("DD"); TestManage.instance.load("EE"); } // Update is called once per frame void Update () { } }
using UnityEngine; using System; using System.Collections; using System.Reflection; public class TestManage { /// <summary> /// 利用 方法配置列表 根据字符串调用对应的方法 /// </summary> /// <param name="para"></param> public void load( string para ) { string[,] strFuns = getFuns(); string result = "can't find anything"; //GetUpperBound可以获取数组的最高下标。 //GetLowerBound可以获取数组的最低下标。 //GetUpperBound 最高下标 应该是长度为4的【3】 for (int i = 0; i < strFuns.GetUpperBound(0)+1; i++) { //Debug.Log( strFuns.GetUpperBound(0) +"---" + strFuns[i, 0]); if (strFuns[i, 0] == para) { string funName = strFuns[i, 1]; myReflection(funName); return; } } Debug.Log(result); } /// <summary> /// 利用反射 通过字符串寻找对应的方法 /// </summary> /// <param name="funName"></param> void myReflection(string funName) { Type t = typeof(TestManage);//获得一个表示MyClass类的Type对象 TestManage reflectOb = this; #region 第二种形式 MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); #endregion foreach (MethodInfo m in mi) { //获得方法参数 ParameterInfo[] pi = m.GetParameters(); if (m.Name.Equals(funName)) { m.Invoke(reflectOb, null); } } } /// <summary> /// 配置方法列表 /// </summary> /// <returns></returns> string[,] getFuns() { string[,] strFuns = new string[,]{ {"AA","AAexc"}, {"BB","BBexc"}, {"CC","CCexc"}, {"DD","DDexc"} }; return strFuns; } public void AAexc() { Debug.Log("i'm AA"); } public void BBexc() { Debug.Log("i'm BB"); } public void CCexc() { Debug.Log("i'm CC"); } public void DDexc() { Debug.Log("i'm DD"); } static TestManage _instance; public static TestManage instance { get { if( _instance == null) { _instance = new TestManage(); } return _instance; } } }