C# 如何利用反射,將字符串轉化為類名並調用類中方法


首先,先隨便創建一個測試類

 

[csharp]  view plain  copy
 
  1. <span style="font-family:Microsoft YaHei;font-size:18px;">public class ABC  
  2. {  
  3.     public void test1()  
  4.     {  
  5.         Debug.Log("test111");  
  6.     }  
  7.   
  8.     public void test2()  
  9.     {  
  10.         Debug.Log("test2222");  
  11.     }  
  12. }</span>  


下面是利用反射技術,將字符串轉化為類名並遍歷類中所有方法(我是在Unity中進行測試的,在C#其他項目中調用也是一樣的)

 

 

[csharp]  view plain  copy
 
  1. <span style="font-family:Microsoft YaHei;font-size:18px;">public class NewBehaviourScript : MonoBehaviour {  
  2.   
  3.     // Use this for initialization  
  4.     void Start () {  
  5.   
  6.         string aa = "ABC";</span>  
[csharp]  view plain  copy
 
  1. <span style="font-family:Microsoft YaHei;font-size:18px;">        Type t;  
  2.   
  3.         t = Type.GetType(aa);  
  4.   
  5.         var obj = t.Assembly.CreateInstance(aa);  
  6. <span style="white-space:pre">    </span>//var obj = System.Activator.CreateInstance(t);  
[csharp]  view plain  copy
 
  1. MethodInfo[] info = t.GetMethods();  
  2.   
  3. for (int i = 0; i < info.Length; i++)  
  4. {  
  5.     info[i].Invoke(obj, null);  
  6. }  
  7. an>  

這么調用將會報出參數數量不匹配的錯誤,如圖:

 

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

 

[csharp]  view plain  copy
 
  1. <span style="font-family:Microsoft YaHei;font-size:18px;">        Debug.Log("方法數量:" + info.Length);  
  2.   
  3.         for (int i = 0; i < info.Length; i++)  
  4.         {  
  5.             string str = info[i].Name;  
  6.             Debug.Log("方法名:" + str);  
  7.         }</span>  

大家注意,反射出來的方法數量其實不是2個,而是6個,C#反射自帶了4個方法,分別是Equals,GetHashCode,GetType,ToString方法,如圖,打印結果為:

 

 

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

 

[csharp]  view plain  copy
 
    1. <span style="font-family:Microsoft YaHei;font-size:18px;">        MethodInfo method = t.GetMethod("test2");  
    2.   
    3.         method.Invoke(obj, null);</span>  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM