• C#通过反射,通过类名、方法名调用方法


    using System;
    using System.Reflection;
    
    class Test
    {
        // 无参数,无返回值方法
        public void Method()
        {
            Console.WriteLine("Method(无参数) 调用成功!");
        }
    
        // 有参数,无返回值方法
        public void Method(string str)
        {
            Console.WriteLine("Method(有参数) 调用成功!参数 :" + str);
        }
    
        // 有参数,有返回值方法
        public string Method(string str1, string str2)
        {
            Console.WriteLine("Method(有参数,有返回值) 调用成功!参数 :" + str1 + ", " + str2);
            string className = this.GetType().FullName;         // 非静态方法获取类名
            return className;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            string strClass = "Test";           // 命名空间+类名
            string strMethod = "Method";        // 方法名
    
            Type type;                          // 存储类
            Object obj;                         // 存储类的实例
    
            type = Type.GetType(strClass);      // 通过类名获取同名类
            obj = System.Activator.CreateInstance(type);       // 创建实例
    
            MethodInfo method = type.GetMethod(strMethod, new Type[] {});      // 获取方法信息
            object[] parameters = null;
            method.Invoke(obj, parameters);                           // 调用方法,参数为空
    
            // 注意获取重载方法,需要指定参数类型
            method = type.GetMethod(strMethod, new Type[] { typeof(string) });      // 获取方法信息
            parameters = new object[] {"hello"};
            method.Invoke(obj, parameters);                             // 调用方法,有参数
    
            method = type.GetMethod(strMethod, new Type[] { typeof(string), typeof(string) });      // 获取方法信息
            parameters = new object[] { "hello", "你好" };
            string result = (string)method.Invoke(obj, parameters);     // 调用方法,有参数,有返回值
            Console.WriteLine("Method 返回值:" + result);                // 输出返回值
    
            // 获取静态方法类名
            string className = MethodBase.GetCurrentMethod().ReflectedType.FullName;
            Console.WriteLine("当前静态方法类名:" + className);
    
            Console.ReadKey();
        }
    }
    BindingFlags  flag  =  BindingFlags.Public  |  BindingFlags.Instance;
    ct  returnValue  =  method.Invoke(dObj,flag,Type.DefaultBinder,parameters,null);

    参考:http://www.imooc.com/article/287955



  • 相关阅读:
    虚拟主机的陷阱
    http://www.xmenglish.com/(外贸知识网站)
    Highlight Table Row
    让你从电脑维修新手到高手
    Flash 视频教程
    ASP Comparison Operators Logical Operators
    Linux 虚拟机 NAT方式上网设置
    vim技巧
    25 条 SSH 命令和技巧
    linux下添加路由的方法
  • 原文地址:https://www.cnblogs.com/wangchuang/p/12202328.html
Copyright © 2020-2023  润新知