在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
using System; using System.Reflection; namespace ConsoleApp2 { class Program { static void Main(string[] args) { //反射获取 命名空间+类名 string className = "ConsoleApp2.ClassSample"; string methodName = "test1"; //传递参数 Object[] paras = new Object[] { "我的", "电脑" }; var t = Type.GetType(className); object obj = Activator.CreateInstance(t); try { #region 方法一 //直接调用 MethodInfo method = t.GetMethod("test2"); method.Invoke(obj, paras); #endregion #region 方法二 MethodInfo[] info = t.GetMethods(); for (int i = 0; i < info.Length; i++) { var md = info[i]; //方法名 string mothodName = md.Name; //参数集合 ParameterInfo[] paramInfos = md.GetParameters(); //方法名相同且参数个数一样 if (mothodName == methodName && paramInfos.Length == paras.Length) { md.Invoke(obj, paras); } } #endregion } catch (Exception ex) { throw ex; } Console.ReadKey(); } } class ClassSample { public void test1(string para1) { Console.WriteLine("方式1 {0}________test111", para1); } public void test1(string para1, string para2) { Console.WriteLine("方式2 {0}________test111________{1}", para1, para2); } public void test2(string para1, string para2) { Console.WriteLine("方式3 {0}________test222________{1}", para1, para2); } } }
|
请发表评论