一种C#的插件式实现(二)

xiaoxiao2021-02-27  190

前面一篇我们介绍了从xml配置中获取要加载的插件。获取插件信息后,需要将插件加载到我们的框架中。 加载插件最重要的一个函数是Activator.CreateInstance,其MSDN介绍如下: // // 摘要: // 使用指定类型的默认构造函数来创建该类型的实例。 // // 参数: // type: // 要创建的对象的类型。 // // 返回结果: // 对新创建对象的引用。 // public static object CreateInstance( Type type); 这里我们对这个函数不做太多介绍,后面介绍插件间的类实现时再详细探讨。 关键代码如下: // 装载程序集 Assembly assembly = Assembly.LoadFrom(file); // 检查程序集中每一个公开的类型 foreach (Type t in assembly.GetExportedTypes()) { // 该类型是否类、是否实现了IParent接口? if (t.IsClass && typeof(IParent).IsAssignableFrom(t)) { // 创建实现了IPlugin接口的类的对象 IParent plugin = Activator.CreateInstance(t) as IParent; ((BaseParent)plugin).m_Interface = Pub.g_IParents; ((BaseParent)plugin).m_IsCanReceiveMsg = true; ((BaseParent)plugin).m_ImageList = Pub.g_ImageList; ((BaseParent)plugin).g_TabControl = Pub.g_TabControl; // 添加到集合中 Pub.g_IParents.Add(plugin); Pub.g_TabControl.TabPages.Add(((BaseParent)plugin).g_Page); ((BaseParent)plugin).g_Page.Image = Pub.g_ImageList.Images[index]; ((BaseParent)plugin).g_Page.Tooltip = PluginsInfo.m_PluginTips[index]; ((BaseParent)plugin).g_SqlConnectionString = Pub.g_SqlConnectionString; DBAccess.DbHelperSQL.connectionString = Pub.g_SqlConnectionString; index++; PubMethods.ClsIniFile.WriteLog("Loading", "LoadingPlugins" + index.ToString(),((BaseParent)plugin).g_Page.Tooltip); } //每个动态库中只能有一个类继承Parent.BaseParent //如果没有继承IParent,则被忽略 else continue; }
转载请注明原文地址: https://www.6miu.com/read-11242.html

最新回复(0)