zoukankan      html  css  js  c++  java
  • 根据方法名执行方法的例子

    今天在讲到动态执行方法的时候,我们讨论到了Delegate.CreateDelegate的方法。但也有下面这样的一个更加通用的方法:可以执行任何方法,传递任意个数的参数,而无需定义delegate

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                //这个例子演示了如何通过methodInfo动态执行方法
    
                MethodInfo mi = typeof(Helper).GetMethod("StaticMethod");
                mi.Invoke(null, null);//因为是静态方法,所以第一个参数直接忽略
    
                MethodInfo mi2 = typeof(Helper).GetMethod("InstanceMethod");
    
                Helper h = new Helper();
                mi2.Invoke(h, null);//因为是实例方法,所以第一个参数是一个对象实例,第二个参数代表了参数
    
    
                MethodInfo mi3 = typeof(Helper).GetMethod("Math");
                int result = (int)mi3.Invoke(h, new object[] { 1, 2 });
                //传递参数并接收结果
                Console.WriteLine(result);
    
    
                Console.Read();
            }
        }
    
        class Helper {
            public static void StaticMethod() {
                Console.WriteLine("静态方法在执行");
            }
    
            public void InstanceMethod() {
                Console.WriteLine("实例方法在执行");
            }
    
            public int Math(int a, int b) {
                return a + b;
            }
        }
    }
    
  • 相关阅读:
    设计模式总结
    内存模型
    运行时内存
    网络
    iOS安全攻防(十)dump自己的app
    iOS安全攻防(九)使用Theos开发SpringBoard的Tweat
    iOS安全攻防(八)Thoes的Logos简介
    iOS安全攻防(七)使用iOSOpenDev开发SpringBoard的Tweat
    iOS安全攻防(六)使用class-dump导出Frameworks头文件
    iOS安全攻防(五)使用dpkg安装deb到iOS设备
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1685179.html
Copyright © 2011-2022 走看看