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>  
原文地址:https://www.cnblogs.com/tsql/p/7986569.html