【问题标题】:Find type from Assembly that implements particular interface从实现特定接口的 Assembly 中查找类型
【发布时间】:2025-12-29 19:00:12
【问题描述】:

我尝试为我的应用程序实现插件系统。这个想法是在一个文件夹中存储用户程序集。当我的应用程序启动时,我想从用户程序集中获取对象列表。

public void InitPlugins()
{
 var userAssemblies = Directory.GetFiles(PATH,"*.dll");
 foreach(var file in userAssemblies)
 {
   Assembly customAssembly = Assembly.Load(file);
   //How can I find all object implements IPlugin in this assembly?       
 }

}

【问题讨论】:

  • 我假设您已经检查了Assembly 类中有趣的方法,例如GetTypes ...您的问题是如何检查给定的类是否实现了接口?旁注:严格来说,程序集包含类型/类而不是对象。
  • 旁注:我已编辑标题以匹配已接受的问题。随意编辑/恢复。

标签: c# plugins reflection


【解决方案1】:

应该可以。

   foreach (Type type in customAssembly )
    {
       if (type.GetInterface("IPlugin") == typeof(IPlugin))
       {
         IPlugin plugin = Activator.CreateInstance(type) as IPlugin;                      
        }
    }

【讨论】:

  • +1。另外我个人会使用GetInterfaces 并检查与Where 匹配的类型,因为这样更容易处理通用和重复的接口名称。
最近更新 更多