1. 程式人生 > >C#通過反射獲取類中的方法和參數個數,反射調用方法帶參數

C#通過反射獲取類中的方法和參數個數,反射調用方法帶參數

new [] 反射 電腦 ram col sta body create

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

C#通過反射獲取類中的方法和參數個數,反射調用方法帶參數