如何加载插件在.NET? [英] How to load plugins in .NET?

查看:185
本文介绍了如何加载插件在.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提供我的软件创建可动态加载的插件的一些方法。 典型的方式做到这一点是使用调用LoadLibrary WinAPI的函数加载一个dll并呼吁 GetProcAddress的得到一个指针,它指向DLL中的函数。

I'd like to provide some way of creating dynamically loadable plugins in my software. Typical way to do this is using the LoadLibrary WinAPI function to load a dll and calling GetProcAddress to get an pointer to a function inside that dll.

我的问题是如何动态地加载插件,在C#/。NET应用程序?

My question is how do I dynamically load a plugin in C#/.Net application?

推荐答案

以下code段(C#)构造从基础派生的任何具体类的实例发现类库(* .dll文件)的应用程序的路径,并将其存储在一个列表中。

The following code snippet (C#) constructs an instance of any concrete classes derived from Base found in class libraries (*.dll) in the application path and stores them in a list.

using System.IO;
using System.Reflection;

List<Base> objects = new List<Base>();
DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);

foreach (FileInfo file in dir.GetFiles("*.dll"))
{
    Assembly assembly = Assembly.LoadFrom(file.FullName);
    foreach (Type type in assembly.GetTypes())
    {
        if (type.IsSubclassOf(typeof(Base)) && type.IsAbstract == false)
        {
            Base b = type.InvokeMember(null,
                                       BindingFlags.CreateInstance,
                                       null, null, null) as Base;
            objects.Add(b);
        }
    }
}

编辑:的通过的马特可能是在.NET 3.5个更好的选择。

The classes referred to by Matt are probably a better option in .NET 3.5.

这篇关于如何加载插件在.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆