公開一個插件接口,如果.DLL或.EXE的代碼中有繼承這個接口就將其示為插件,并將這些插件放在同一目錄。運行程序的時候掃描目 錄并通過反射判斷.DLL或.EXE中是否存在該接口,若存在,則當作插件加載進來。如下圖示
1.定義命令接口
public interface ICommand { ServerReturn execute(); ServerReturn Rollback(); }
獲取當前目錄下繼承該接口的方法
public List<ICommand> CommandList() { List<ICommand> ICommandList = new List<ICommand>(); string[] files = Directory.GetFiles(System.IO.Directory.GetCurrentDirectory()); int i = 0; foreach (string file in files) { string ext = file.Substring(file.LastIndexOf(".")); if (ext != ".dll") continue; try { // 加載插件 Assembly tmp = Assembly.LoadFile(file); Type[] types = tmp.GetTypes(); bool ok = false; foreach (Type t in types) if (IsValidCommand(t)) { // 通過反射實例化 ICommand plugin = (ICommand)tmp.CreateInstance(t.FullName); ICommandList.Add(plugin); ok = true; if (ok) break; } } catch (Exception err) { throw err; } } return ICommandList; } /// <summary> /// 判斷DLL中是否繼承了ICommand接口 /// </summary> /// <param name="t"></param> /// <returns></returns> PRivate static bool IsValidCommand(Type t) { bool ret = false; Type[] interfaces = t.GetInterfaces(); foreach (Type theInterface in interfaces) { if (theInterface.FullName == "ClassDemo.ICommand") { ret = true; break; } } return ret; }
職責鏈執行方法組
/// <summary> /// 方法執行 /// </summary> public void exec() { List<ICommand> list = new List<ICommand>(); foreach( ICommand demo in list) { if(!demo.execute().isSurccess) { demo.Rollback(); return; } } }
|
新聞熱點
疑難解答