代码之家  ›  专栏  ›  技术社区  ›  Hubert Solecki

无法在运行时从程序集获取方法

  •  2
  • Hubert Solecki  · 技术社区  · 6 年前

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

    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;
        }
    
      }
     }
    

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

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

    2 回复  |  直到 6 年前
        1
  •  2
  •   DavidG    6 年前

    这里有几个问题。首先 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");
    
        2
  •  0
  •   Ermindo Lopes    6 年前

    问题是“静态”的

    static bool Execute(string contactName)
    

    把它当作

    public bool Execute(string contactName)