C#通过反射获取类中的方法和参数个数,反射调用方法带参数

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);
        }
    }
}

 

转载于:https://www.cnblogs.com/smartsmile/p/8474545.html

你可能感兴趣的:(c#)