问题描述
我是C#的初学者。下面代码是我复制自MSDN中的。运行时,在“Objectret=m.Invoke(o,newObject[]{42});”处有错误提示:未处理的TargetException:非静态方法需要一个目标这个问题,怎么解决?谢谢usingSystem;usingSystem.Configuration;usingSystem.Security.Permissions;usingSystem.Reflection;namespaceConsoleApplication1{[assembly:AssemblyVersionAttribute("1.0.2000.0")]publicclassExample{privateintfactor;publicExample(intf){factor=f;}publicintSampleMethod(intx){Console.WriteLine("nExample.SampleMethod({0})executes.",x);returnx*factor;}publicstaticvoidMain(){Assemblyassem=Assembly.GetExecutingAssembly();Console.WriteLine("AssemblyFullName:");Console.WriteLine(assem.FullName);//TheAssemblyNametypecanbeusedtoparsethefullname.AssemblyNameassemName=assem.GetName();Console.WriteLine("nName:{0}",assemName.Name);Console.WriteLine("Version:{0}.{1}",assemName.Version.Major,assemName.Version.Minor);Console.WriteLine("nAssemblyCodeBase:");Console.WriteLine(assem.CodeBase);//Createanobjectfromtheassembly,passinginthecorrectnumber//andtypeofargumentsfortheconstructor.Objecto=assem.CreateInstance("Example",false,BindingFlags.ExactBinding,null,newObject[]{2},null,null);//Makealate-boundcalltoaninstancemethodoftheobject.MethodInfom=assem.GetType("ConsoleApplication1.Example").GetMethod("SampleMethod");Objectret=m.Invoke(o,newObject[]{42});//出错的地方Console.WriteLine("SampleMethodreturned{0}.",ret);Console.WriteLine("nAssemblyentrypoint:");Console.WriteLine(assem.EntryPoint);Console.ReadLine();}}}
解决方案
解决方案二:
Objecto=assem.CreateInstance("Example",false,你的o是null吧,没有创建成功
解决方案三:
Objecto=assem.CreateInstance("Example",false,BindingFlags.ExactBinding,null,newObject[]{2},null,null);Objecto=assem.CreateInstance("ConsoleApplication1.Example",false,BindingFlags.ExactBinding,null,newObject[]{2},null,null);你通过反射创建对象的时候,没有成功,返回的是Null,原因是你的typeName错了.要写全,谢谢.切记.
解决方案四:
本帖最后由 bdmh 于 2012-03-12 10:29:43 编辑