根据方法名执行方法的例子(转)

  http://www.cnblogs.com/chenxizhang/archive/2010/03/13/1685179.html

今天在讲到动态执行方法的时候,我们讨论到了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;
        }
    }
}

 

posted @ 2013-03-24 13:00  C#老头子  Views(291)  Comments(0Edit  收藏  举报