記錄一下C#插件式開發。
原理:主要模塊【運行DLL(共享DLL)】、【界面主程序】、【插件DLL】
原理沒時間寫太詳細,以后有機會再補充吧,先上傳代碼。
以下是C#DLL程序集代碼,命名為【Runtime】
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Runtime { public interface IAdd { int Add(int a, int b); } }
以下是C#DLL程序集代碼,命名為【Plugin】
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Runtime; namespace Plugin { public class Operation : IAdd { public int Add(int a, int b) { return a + b; } } }
以下是C#Console程序集代碼,命名為為【Main】
using Runtime; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Main { class Program { static void Main(string[] args) { string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll"); // 遍歷所有的dll文件,可以自己規定插件名稱(比如“*.plugin.dll” = "123.plugin.dll") 進行過濾 foreach (string fn in files) { // 獲取程序集 Assembly ass = Assembly.LoadFrom(fn); // 獲取所有類,但是此處並沒有被實例化。 foreach (Type pClass in ass.GetTypes()) { // 判斷該類是否是實現了接口 if (pClass.GetInterface("IAdd") == (typeof(IAdd))) { // 創建實例類 object obj = ass.CreateInstance(pClass.FullName); // 獲取類方法 MethodInfo fun = pClass.GetMethod("Add"); // 執行類方法 object result = (int)fun.Invoke(obj, new object[] { 1, 30 }); Console.WriteLine(result); } } } Console.ReadLine(); } } }