GetType(“ClassName).GetMethod(“MethodName”) 抛出错误

本文关键字:出错 错误 GetMethod ClassName GetType MethodName | 更新日期: 2023-09-27 18:33:34

我正在尝试了解有关程序集类及其方法的更多信息,并且此URL上有一个示例

,如下所示:

但是,method: assem.GetType("Example").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,区域性=中性,公钥令牌=空

名称:来源版本: 1.0

汇编代码库:file:///C:/sdtree/AssemblyClass/cs/source.exe

示例.SampleMethod(42) 执行。采样方法返回 84。

程序集入口点:Void Main() */

GetType(“ClassName).GetMethod(“MethodName”) 抛出错误

如果你看看Assembly.CreateInstance方法(你可以在这里找到描述)您可以在以下代码中看到:

 Object o = assem.CreateInstance("Example", false, 
        BindingFlags.ExactBinding, 
        null, new Object[] { 2 }, null, null);

你根本没有真正为"o"分配任何值。

然后,正如我之前所说,您不会通过以下方式返回它:

assem.GetType("Example")

添加命名空间将真正解决问题。

将来,尝试隔离问题以找出问题所在。 simlpy 帮助调试

相关文章: