天天看點

C# 如何利用反射,将字元串轉化為類名并調用類中方法

首先,先随便建立一個測試類

<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);
        }
}</span>
           

這麼調用将會報出參數數量不比對的錯誤,如圖:

C# 如何利用反射,将字元串轉化為類名并調用類中方法

我們加入下面幾行代碼,就會恍然大悟。

<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方法,如圖,列印結果為:

C# 如何利用反射,将字元串轉化為類名并調用類中方法

如果不想周遊全部方法的話,也可以指定方法名進行調用,添加如下代碼即可

<span style="font-family:Microsoft YaHei;font-size:18px;">        MethodInfo method = t.GetMethod("test2");

        method.Invoke(obj, null);</span>