C# 反射,通過類名、方法名調用方法


 

在 C# 代碼中,有些時候只知道方法的名字(string),需要調用該方法,那么就需要用到 C# 的反射機制。下面是一個簡單的 demo。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM