首页 > 解决方案 > 在运行时无法从程序集中获取方法

问题描述

我正在使用以下代码在运行时加载程序集,然后获取对特定方法的引用并在最后执行它:

var assemblyLoaded = Assembly.LoadFile(absolutePath);
var type = assemblyLoaded.GetType("CreateContactPlugin.Plugin");

var instance = Activator.CreateInstance(type);

var methodInfo = type.GetMethod("Execute", new Type[] { typeof(System.String)});
if (methodInfo == null)
{
    throw new Exception("No such method exists.");
}

这是我要调用的程序集

namespace CreateContactPlugin
{
   public class Plugin
   {

    static bool Execute(string contactName){
        bool contactCreated = false;
        if (!String.IsNullOrWhiteSpace(contactName))
        {
            //process
        }
        return contactCreated;
    }

  }
 }

我可以成功加载程序集,类型。当我突出显示类型变量时,我看到了 DeclaredMethods 数组中列出的方法。但是当我尝试获取方法时,它总是返回 null。

有人看到我在这里可能做错了吗?

标签: c#reflectionruntime.net-assembly

解决方案


这里有几个问题。首先Execute方法是static而不是public所以你需要指定正确的绑定标志来获得它。

var methodInfo = type.GetMethod("Execute", BindingFlags.Static | BindingFlags.NonPublic);

但是,使用较少反射和强类型的替代(并且在我看来更可取)解决方案是让您的插件类实现一个通用接口,这样您就可以强类型您的instance对象。首先制作一个包含相关接口的类库,例如:

public interface IContactPlugin
{
    bool Execute(string contactName);
}

现在你的插件也可以引用同一个库,变成这样:

namespace CreateContactPlugin
{
    public class Plugin : IContactPlugin
    {
        public bool Execute(string contactName)
        {
            //snip
        }
    }
}

你的调用代码现在是这样的:

var assemblyLoaded = Assembly.LoadFile(absolutePath);
var type = assemblyLoaded.GetType("CreateContactPlugin.Plugin");

var instance = Activator.CreateInstance(type) as IContactPlugin;

if (instance == null)
{
    //That type wasn't an IContactPlugin, do something here...
}

instance.Execute("name of contact");

推荐阅读