一种C#的插件式实现(一)_读取xml配置

对于插件式框架的优缺点本文不再赘述,也不在本文的讨论范围,本文仅介绍一种C# 插件式实现的步骤。
本文描述的插件式基本流程如下:
1.配置插件
2.读取配置中的插件
3.按照约定的接口进行加载插件

配置插件主要考虑对于c# 中动态库一般使用dll作为后缀,而其他非插件的动态库加载时可能会比较耗时,因此采用配置方式。其中配置文件如下:
<?xml version="1.0" encoding="utf-8" ?>
MainPage.dll主页.png1主页主页
    trueSysManager.dll系统管理.png1系统管理系统管理
    trueYPGL.dll药品管理.png1药品管理药品管理
    trueMZSF.dll门诊收费.png1门诊收费门诊收费
    trueTJCX.dll统计查询.png1统计查询统计查询
    trueJCZL.dll基础资料.png1基础资料基础资料
    trueYGXXGL.dll基础资料.png1员工信息管理员工信息管理
    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是全局变量,不影响代码的阅读,保留。最后将附上整个工程源码。

猜你喜欢

转载自blog.csdn.net/eqmaster/article/details/77723420
今日推荐