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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值