C# GetType(";ClassName).GetMethod(";MethodName";)抛出错误
我试图了解更多关于Assembly类及其方法的信息,下面是一个示例: 但是,方法:C# GetType(";ClassName).GetMethod(";MethodName";)抛出错误,c#,.net-assembly,C#,.net Assembly,我试图了解更多关于Assembly类及其方法的信息,下面是一个示例: 但是,方法:assem.GetType(“示例”).GetMethod(“SampleMethod”)抛出异常错误,并抱怨没有对象引用 似乎此方法之前的方法也返回null。有什么想法吗 using System; using System.Reflection; using System.Security.Permissions; [assembly:AssemblyVersionAttribute("1.0.2000.0"
assem.GetType(“示例”).GetMethod(“SampleMethod”)
抛出异常错误,并抱怨没有对象引用
似乎此方法之前的方法也返回null。有什么想法吗
using System;
using System.Reflection;
using System.Security.Permissions;
[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);
}
}
/*此代码示例生成类似以下内容的输出:
程序集全名:
源代码,版本=1.0.2000.0,区域性=中立,PublicKeyToken=null
姓名:来源
版本:1.0
汇编代码库:
file:///C:/sdtree/AssemblyClass/cs/source.exe
示例。执行SampleMethod(42)。
SampleMethod返回84
装配入口点:
Void Main()
*/如果您查看Assembly.CreateInstance方法(您可以找到描述) 您可以在该代码中看到:
Object o = assem.CreateInstance("Example", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);
你只是没有真正赋予“o”任何价值
那么,正如我之前所说,您不能通过以下方式退回:
assem.GetType("Example")
添加名称空间将真正解决这个问题
将来,尝试隔离问题,找出问题所在。simlpy帮助调试我猜
GetType(..)
返回null。请隔离实际问题-如果GetType确实返回null,那么GetMethod是完全无关的。。。一个不起作用的程序呢?(这段代码对我来说绝对有效……现在还不清楚您是否正在运行这段代码并遇到问题,或者是什么……)如果我将这段代码放在一个名称空间中,我可以重现这段代码。因此,-1表示不包括实际代码。