Dot-Net
如何在 .NET 中載入外掛?
我想提供一些在我的軟體中創建動態可載入外掛的方法。執行此操作的典型方法是使用LoadLibrary WinAPI 函式載入 dll 並呼叫GetProcAddress以獲取指向該 dll 內函式的指針。
我的問題是如何在 C#/.Net 應用程序中動態載入外掛?
以下程式碼片段 (C#) 構造派生
Base自在應用程序路徑中的類庫 (*.dll) 中找到的任何具體類的實例,並將它們儲存在列表中。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); } } }編輯:Matt提到的類可能是 .NET 3.5 中更好的選擇。
從 .NET 3.5 開始,有一種正式的、內置的方法可以從 .NET 應用程序創建和載入外掛。這一切都在System.AddIn命名空間中。有關更多資訊,您可以查看 MSDN 上的這篇文章:載入項和可擴展性