根据方法名获取方法并动态执行

  1. 根据方法名获取方法
  2. 重载方法的获取
  3. 重载方法的执行
  4. 静态方法与实例方法的执行区别
using System;
using System.Reflection;

namespace DynimicExecutionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(User)
            ///获取Name属性的get和set方法
            MethodInfo set_Name = type.GetMethod("set_Name");
            MethodInfo get_Name = type.GetMethod("get_Name");
            ///获得含有重载的方法
            /// 重载方法中的参数列表类型要通过GetMethod方法参数传入
            MethodInfo say = type.GetMethod("Say",new Type[] {});
            MethodInfo say_Msg = type.GetMethod("Say", new Type[] { typeof(string)});

            MethodInfo add = type.GetMethod("Add");
            MethodInfo print = type.GetMethod("Print");


            var user = new User();
            Console.WriteLine(get_Name.Invoke(user,null));
            ///非静态方法调用时第一个参数必须传入方法所在对象的实例
            /// 第二个参数为调用方法的参数列表数组
            set_Name.Invoke(user, new object[] { "张三" });
            Console.WriteLine(get_Name.Invoke(user, null));

            say.Invoke(user, null);
            say_Msg.Invoke(user, new object[] {"你好"});

            var result = (int)add.Invoke(user, new object[] {1, 2});
            Console.WriteLine(result);

            /// 静态方法调用时第一个参数可以传入null
            print.Invoke(null, null);

            Console.ReadKey();

        }
    }

    public class User
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public void Say()
        {
            Console.WriteLine("Hello");
        }

        public void Say(string msg)
        {
            Console.WriteLine(msg);
        }

        public int Add(int a, int b)
        {
            return a + b;
        }

        public static void Print()
        {
            Console.WriteLine("static print method");
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值