对于插件式框架的优缺点本文不再赘述,也不在本文的讨论范围,本文仅介绍一种C# 插件式实现的步骤。
本文描述的插件式基本流程如下:
1.配置插件
2.读取配置中的插件
3.按照约定的接口进行加载插件
配置插件主要考虑对于c# 中动态库一般使用dll作为后缀,而其他非插件的动态库加载时可能会比较耗时,因此采用配置方式。其中配置文件如下:
MainPage.dll
主页.png
1
主页
主页
true
SysManager.dll
系统管理.png
1
系统管理
系统管理
true
YPGL.dll
药品管理.png
1
药品管理
药品管理
true
MZSF.dll
门诊收费.png
1
门诊收费
门诊收费
true
TJCX.dll
统计查询.png
1
统计查询
统计查询
true
JCZL.dll
基础资料.png
1
基础资料
基础资料
true
YGXXGL.dll
基础资料.png
1
员工信息管理
员工信息管理
true
读取该插件配置的关键代码如下:
private static void GetPlugins()
{
List
stringPaths = new List
();
List
stringTips = new List
();
List
stringVisibles = new List
(); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); string xmlfile = System.Windows.Forms.Application.StartupPath + "\\cfg\\default.xml"; if (!System.IO.File.Exists(xmlfile)) { System.Windows.Forms.MessageBox.Show("配置文件不存在,初始化菜单失败" + System.Windows.Forms.Application.StartupPath + "\\Config\\menu.xml"); System.Environment.Exit(0); } xmlDoc.Load(xmlfile); System.Xml.XmlNodeList nodePlugins = xmlDoc.SelectSingleNode("plugins").ChildNodes;//获取plugins节点 foreach (System.Xml.XmlNode plugin in nodePlugins)//遍历所有 plugin { System.Xml.XmlElement attributes = (System.Xml.XmlElement)plugin; foreach (System.Xml.XmlNode attribute in attributes)//所有的plugin属性 { if (attribute.Name.ToUpper() == "NAME") { stringPaths.Add(System.Windows.Forms.Application.StartupPath + "\\plugins\\" + attribute.InnerText); } if (attribute.Name.ToUpper() == "IMGPATH") { Image img = System.Drawing.Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\img\\" + attribute.InnerText,true); Pub.g_ImageList.Images.Add(attribute.InnerText, img); } if (attribute.Name.ToUpper() == "TIP") { stringTips.Add(attribute.InnerText); } if (attribute.Name.ToUpper() == "VISIBLE") { stringVisibles.Add(attribute.InnerText); } } } PluginsInfo.m_PluginPaths = stringPaths.ToArray(); PluginsInfo.m_PluginTips = stringTips.ToArray(); PluginsInfo.m_stringVisibles = stringVisibles.ToArray(); }
其中PluginsInfo是全局变量,不影响代码的阅读,保留。最后将附上整个工程源码。