我想提供我的软件创建可动态加载的插件的一些方法。 典型的方式做到这一点是使用调用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.
相关推荐
最新文章