首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

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

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

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);//这里第一个参数是这个委托的实例,后面的是参数. 

热点排行