Mono addin 学习笔记 2

下面分析用xml描述文件的方式来进行插件定义

定义扩展点如下:

public interface ISnippetProvider  

{   

     string GetText (string shortcut);  

}

下面定义基于该扩展点的扩展如下:

 class StockSnippetProvider: ISnippetProvider  

{      

       public string GetText (string shortcut)     

        {            

               foreach (ExtensionNode<SnippetAttribute> node in AddinManager.GetExtensionNodes("/SnippetsAddinNode/StockSnippets"))           

              {                 

                    if (node.Data.Shortcut == shortcut)                     

                          return node.Data.Text;            

               }            return null;     

        }  

}

//定义扩展属性如下:

 [AttributeUsage (AttributeTargets.Assembly, AllowMultiple=true)]  

public class SnippetAttribute : CustomExtensionAttribute  

{   

       public SnippetAttribute ()   

       {   }

       public SnippetAttribute ([NodeAttribute ("Shortcut")] string shortcut, [NodeAttribute ("Text")] string text)  

       {   

            Shortcut = shortcut;            

            Text = text;   

       }

      [NodeAttribute]  

      public string Shortcut { get; set; }

      [NodeAttribute]  

      public string Text { get; set; }  

}

到目前位置,扩展点和扩展都已经定义好了,现在使用xml文件来将进行插件的定义,具体如下:

<addin id="SnippetsAddinNode" version="1.0" >

     <Dependencies>    

             <Addin id="TextEditorExtensionNode.Core" version="1.0"/>  

      </Dependencies>

     <ExtensionPoint path="/SnippetsAddinNode/StockSnippets"  name="StockSnippets">    

            <ExtensionNode name="Command"/>  

      </ExtensionPoint>    

      <Extension path = "/SnippetsAddinNode/StockSnippets">    

                 <Command  type="SnippetAttribute"  Shortcut="c"  Text="Hello"/>    

                 <Command  type="SnippetAttribute"  Shortcut="for"  Text="for (int n=0; n &lt len; n++) { =&lt|&gt }"/>    

                 <Command  type="SnippetAttribute"  Shortcut="foreach"  Text="foreach (var item in col) { &lt|&gt }"/>  

       </Extension>  

</addin>

使用扩展点的代码如下:

foreach (ISnippetProvider provider in AddinManager.GetExtensionObjects <ISnippetProvider>())

{     

       string fullText = provider.GetText (word);    

}

注意: xml配置方式定义的扩展点,支持以嵌入式资源方式和程序集一起发布,也支持配置文件以单独的文件的方式来部署

下一篇将详细参数扩展点的几种方式

原文地址:https://www.cnblogs.com/lenmom/p/3594130.html