TargetException异常的处理
我是C#的初学者。下面代码是我复制自MSDN中的。运行时,
在 “ Object ret = m.Invoke(o, new Object[] { 42 }); ”处
有错误提示:
未处理的TargetException : 非静态方法需要一个目标
这个问题,怎么解决?
谢谢
using System;
using System.Configuration;
using System.Security.Permissions;
using System.Reflection;
namespace ConsoleApplication1
{
[assembly: AssemblyVersionAttribute("1.0.2000.0")]
public class Example
{
private int factor;
public Example(int f)
{
factor = f;
}
public int SampleMethod(int x)
{
Console.WriteLine("\nExample.SampleMethod({0}) executes.", x);
return x * factor;
}
public static void Main()
{
Assembly assem = Assembly.GetExecutingAssembly();
Console.WriteLine("Assembly Full Name:");
Console.WriteLine(assem.FullName);
// The AssemblyName type can be used to parse the full name.
AssemblyName assemName = assem.GetName();
Console.WriteLine("\nName: {0}", assemName.Name);
Console.WriteLine("Version: {0}.{1}",
assemName.Version.Major, assemName.Version.Minor);
Console.WriteLine("\nAssembly CodeBase:");
Console.WriteLine(assem.CodeBase);
// Create an object from the assembly, passing in the correct number
// and type of arguments for the constructor.
Object o = assem.CreateInstance("Example", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);
// Make a late-bound call to an instance method of the object.
MethodInfo m = assem.GetType("ConsoleApplication1.Example").GetMethod("SampleMethod");
Object ret = m.Invoke(o, new Object[] { 42 }); //出错的地方
Console.WriteLine("SampleMethod returned {0}.", ret);
Console.WriteLine("\nAssembly entry point:");
Console.WriteLine(assem.EntryPoint);
Console.ReadLine();
}
}
} --------------------编程问答-------------------- Object o = assem.CreateInstance("Example", false,
你的 o 是null吧,没有创建成功 --------------------编程问答-------------------- Object o = assem.CreateInstance("Example", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);
Object o = assem.CreateInstance("ConsoleApplication1.Example", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);
你通过反射创建对象的时候,没有成功,返回的是Null, 原因是你的typeName错了.要写全,谢谢.切记. --------------------编程问答--------------------
补充:.NET技术 , C#