c#代码中的错误
下面是MSDN的例程。但当我将运行它时,它却报错。在 MethodInfo m = assem.GetType("Example").GetMethod("SampleMethod");
一行出现“未处理NullReferenceException”的错误
请问,是什么原因?应该怎样解决?
谢谢
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("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();
}
}
}
--------------------编程问答-------------------- MethodInfo m = assem.GetType("Example").GetMethod("SampleMethod");
检查assem.GetType("Example")是否得到,然后GetMethod是否得到,肯定是没有得到,访问了空对象 --------------------编程问答-------------------- assem.GetType("Example").GetMethod("SampleMethod");
assem=null或者assem.GetType("Example")=null --------------------编程问答-------------------- MethodInfo m = assem.GetType("color=#FF0000]ConsoleApplication1.[[/color]Example").GetMethod("SampleMethod");
要带命名空间 --------------------编程问答-------------------- MethodInfo m = assem.GetType("ConsoleApplication1.Example").GetMethod("SampleMethod");
补充:.NET技术 , C#