2. 插件信息的存储与获取
一个插件需要有它的名称 、版本等信息。作为设计者的你,也一定要留下你的尊姓大名和个人网站等用来宣传自己。 C# 的新特性——属性, 就是一个很好的解决方案。因此我们定义一个从 System.Attribute 继承来的类 PluginInfoArrtibute :
/// /// 用来指定一个插件的相关信息 /// public class PluginInfoAttribute : System.Attribute { /// /// Deprecated. Do not use. /// public PluginInfoAttribute() {} public PluginInfoAttribute( string name , string version , string author , string webpage , bool loadWhenStart ) { // 细节已略去 } public string Name { get { return _Name; } } public string Version { get { return _Version; } } public string Author { get { return _Author; } } public string Webpage { get { return _Webpage; } } public bool LoadWhenStart { get { return _LoadWhenStart; } } /// /// 用来存储一些有用的信息 /// public object Tag { get { return _Tag; } set { _Tag = value ; } } /// /// 用来存储序号 /// public int Index { get { return _Index; } set { _Index = value ; } } private string _Name = ""; private string _Version = ""; private string _Author = ""; private string _Webpage = ""; private object _Tag = null ; private int _Index = 0; // 暂时不会用 private bool _LoadWhenStart = true ; } |
用这个类修饰你的插件,并让他实现 IPlugin 接口:
/// /// My Pluging 1( Just for test ) /// [ PluginInfo("My Pluging 1( Just for test )" ,"1.0" , "Jack H Hansen" , "http://blog.csdn.net/matrix2003b" , true ) ] public class MyPlugin1 : IPlugin { public MyPlugin1() { } #region IPlugin 成员 // 细节已略去 #endregion private IApplicationObject _App; private IDocumentObject _CurDoc; } |
3. 加载插件
现在就得用到 System.Refelction 命名空间了。程序在启动时会搜索 plugins 目录下的每一个文件。对于每一个文件,如果它是一个插件,就用 Assembly 对象加载它。然后枚举程序集中的每一个对象。判断一个程序集是否为我们的插件的方法是判断它是否直接或间接实现自 IPlugin。用下面的函数,传递从程序集枚举的对象的System.Type。
private bool IsValidPlugin( Type t ) { bool ret = false ; Type[] interfaces = t.GetInterfaces(); foreach ( Type theInterface in interfaces ) { if ( theInterface.FullName == "CSPluginKernel.IPlugin" ) { ret = true ; break ; } } return ret; } |
若条件都满足,IsValidPlugin() 就会返回 true 。接着程序就会创建这个对象并把它存于一个 ArrayList 中。
plugins.Add( pluginAssembly.CreateInstance( plugingType.FullName ) ); |
现在,你就可以撰写测试代码了。