C# 反射通过类名与方法名调用类与方法

C# 反射通过类名与方法名调用类与方法

using System; using System.Linq; using System.Text; {     {     }     {     }

    public string Method(string str1, string str2)//3         string className1 = this.GetType().FullName;//非静态方法中获取类名         Console.WriteLine("3:_;类名"+className1+""+ className2);     } class Program     public static void run(string testcase)         string strClass = "test";  //命名空间+类名
        string strMethod = "Method";//方法名

        Type type;
        object obj;

        type = Type.GetType(strClass);//通过string类型的strClass获得同名类“type”
        obj = System.Activator.CreateInstance(type);//创建type类的实例 "obj"

        MethodInfo method = type.GetMethod(strMethod, new Type[] { });//取的方法描述//通过string类型的strMethod获得同名的方法“method”//1
        method.Invoke(obj, null);//type类实例obj,调用方法"method"//1

        method = type.GetMethod(strMethod, new Type[] { typeof(String) });//取的方法描述//2         method.Invoke(obj, objs);//t类实例obj,调用方法"method(testcase)"//2

        method = type.GetMethod(strMethod, new Type[] { typeof(String), typeof(String) });//取的方法描述//2         Console.WriteLine(result);//3

        //string className = this.GetType().FullName;         Console.WriteLine(className);     }     {         run(testcase); }

posted @ 2020-12-30 11:16  SunKeep  阅读(345)  评论(0)    收藏  举报