首先,先隨便創建一個測試類
- <span style="font-family:Microsoft YaHei;font-size:18px;">public class ABC
- {
- public void test1()
- {
- Debug.Log("test111");
- }
- public void test2()
- {
- Debug.Log("test2222");
- }
- }</span>
下面是利用反射技術,將字符串轉化為類名並遍歷類中所有方法(我是在Unity中進行測試的,在C#其他項目中調用也是一樣的)
- <span style="font-family:Microsoft YaHei;font-size:18px;">public class NewBehaviourScript : MonoBehaviour {
- // Use this for initialization
- void Start () {
- string aa = "ABC";</span>
- <span style="font-family:Microsoft YaHei;font-size:18px;"> Type t;
- t = Type.GetType(aa);
- var obj = t.Assembly.CreateInstance(aa);
- <span style="white-space:pre"> </span>//var obj = System.Activator.CreateInstance(t);
- MethodInfo[] info = t.GetMethods();
- for (int i = 0; i < info.Length; i++)
- {
- info[i].Invoke(obj, null);
- }
- an>
這么調用將會報出參數數量不匹配的錯誤,如圖:

我們加入下面幾行代碼,就會恍然大悟。
- <span style="font-family:Microsoft YaHei;font-size:18px;"> Debug.Log("方法數量:" + info.Length);
- for (int i = 0; i < info.Length; i++)
- {
- string str = info[i].Name;
- Debug.Log("方法名:" + str);
- }</span>
大家注意,反射出來的方法數量其實不是2個,而是6個,C#反射自帶了4個方法,分別是Equals,GetHashCode,GetType,ToString方法,如圖,打印結果為:
如果不想遍歷全部方法的話,也可以指定方法名進行調用,添加如下代碼即可
- <span style="font-family:Microsoft YaHei;font-size:18px;"> MethodInfo method = t.GetMethod("test2");
- method.Invoke(obj, null);</span>
