日期:2014-05-18  浏览次数:21690 次

C# 中,执行反射出来的方法,出现异常:非静态方法需要一个目标,源码示例
C# code
        ...............

        private delegate void MyMethodHandler();//delegate

        private event MyMethodHandler MyMethodEvent;//event

        private void Method()
        {
            MyMethodEvent+=Method1();
            MyMethodEvent+=Method2();
            MyMethodEvent+=Method3();
            MyMethodEvent+=Method4();
            MyMethodEvent+=Method5();
            Delegate[] delegates = MyMethodEvent.GetInvocationList();
            for (int i = 0; i < delegates.Length; i++)
            {
                MethodInfo methodInfo = delegates[i].Method;
                methodInfo.Invoke(null, null);//这里有异常,未处理TargetException,非静态方法需要一个目标。
            }
        }

        private viod Method1(){//nothing to do...this is demo...}
        private viod Method2(){//nothing to do...this is demo...}
        private viod Method3(){//nothing to do...this is demo...}
        private viod Method4(){//nothing to do...this is demo...}
        private viod Method5(){//nothing to do...this is demo...}

        ..............


------解决方案--------------------
反射,创建一个对象。用对象调用
------解决方案--------------------
methodInfo.Invoke(this,null);
------解决方案--------------------
C# code

methodInfo.Invoke(null, null);//这里第一个参数是这个委托的实例,后面的是参数.