通过名称查找类失败,GetMethod调用抛出NullReferenceException

本文关键字:调用 GetMethod NullReferenceException 失败 查找 | 更新日期: 2023-09-27 18:07:50

我有我的DLL:

using System;
namespace DLLtest
{
    public static class TestDll
    {
        public static void TestVoid()
        {
            Console.WriteLine("TestVoid called");
        }
    }
}

在我的程序中,我做的是:

Assembly a = Assembly.LoadFile(
     Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DLLtest.dll"));
var b = a.GetType("TestDll").GetMethod("TestVoid");
b.Invoke(null, new object[] { });

我得到NullReferenceException"var b..."行(确实有些东西是空的是什么是NullReferenceException,以及我如何修复它?

我尝试添加BindingFlags,但总是相同的错误…

通过名称查找类失败,GetMethod调用抛出NullReferenceException

类型的名称是DLLTest.TestDll -所以你得到null只搜索TestDll

修复:

  • 使用完整的类名
  • 从程序集获取所有类型,并通过匹配部分名称查找类型。