c# - 在运行时无法从程序集中获取方法
问题描述
我正在使用以下代码在运行时加载程序集,然后获取对特定方法的引用并在最后执行它:
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。
有人看到我在这里可能做错了吗?
解决方案
这里有几个问题。首先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");
推荐阅读
- bash - 在没有 Python 的情况下生成 Jupyter Notebook 密码
- karate - 具有默认值的嵌入式表达式 (JSON/YML)
- python - 如何使用numpy根据向量索引条件获取布尔二维数组?
- kubernetes - aws ebs csi 驱动程序无法使用附加到 ec2-instance 的 IAM 角色创建持久卷
- security - 我如何才能完全信任 SAML IDP?
- php - PHP CS Fixer - 丑陋的缩进
- python-3.x - 无法根据条件获取索引
- r - 将脚注文本添加到各个医院的 ggplot2 图表
- python-3.x - Django:如何在不删除数据库的情况下将 cat_id 更改为 cat_slug?
- javascript - 我的 index.js 文件缺少 app.js 文件的哪一部分?