C# 插件开发

//1 定义插件接口,将其编译成 dll,例如:
using  System;
  
namespace  PluginInterface
{
  public  interface  IShow
  {
   string  Show() ;
  }
}
  
  
//2 编写插件. 新建dll工程,并引用第一步做的dll插件,实现其接口,例如:
namespace  PluginA
{
  public  class  PluginA : PluginInterface.IShow
  {
   public  string  Show()
   {
    return  "I am plugin A"  ;
   }
  }
}
//3. 在指定目录下寻找Dll文件
private  void  frmMain_Load( object  sender, System.EventArgs e)
{
     //获取Plugins目录中所有的DLL文件,并保存在combo中
                     try
     {
         string  path = Application.StartupPath ;
         path  = System.IO.Path.Combine(path, "Plugins" ) ;
         foreach  string  file  in  System.IO.Directory.GetFiles(path, "*.dll" ))
         {
             this .cmbPlugins.Items.Add(file) ;
         }
     }
     catch  (Exception ex)
     {
         MessageBox.Show(ex.Message ) ;
     }
  
// 使用插件
privatevoid btnExecute_Click(object sender, System.EventArgs e)
{
try
{
//1. 获得 文件名称

string asmFile = this.cmbPlugins.Text ;
string asmName = System.IO.Path.GetFileNameWithoutExtension(asmFile) ;
if ( asmFile != string.Empty )
{

//2. 利用反射,构造DLL文件的实例

System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom(asmFile) ;

//3. 利用反射,从程序集(DLL)中,提取类,并把此类实例化

PluginInterface.IShow iShow = (PluginInterface.IShow)
System.Activator.CreateInstance(asm.GetType(asmName + "Namespace." + asmName+"Class")) ;

//4. 在主程序中使用这个类的实例

this.label2.Text = iShow.Show();
}
}

catch ( Exception ex )
{
MessageBox.Show(ex.Message ) ;
}
}

转载于:https://www.cnblogs.com/jiaocheng/p/4770848.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值