C# 简易插件开发演示[控制台程序]

//定义主程序插件接口
namespace PluginInterface
{
    public interface PluginInterface
    {
        void printf();
    }
}

编译插件接口 : csc /out:PluginInterface.dll /t:library PluginInterface.cs

//插件PluginA
using System;
namespace PluginA
{
    public class PluginA : PluginInterface.PluginInterface
    {
        public void printf()
        {
            Console.WriteLine("This is string for Plugin");
        }
    }
}

把PluginInterface.dll复制到PluginA.cs下。

编译PluginA : csc /out:PluginA.dll /t:library /r:PluginInterface.dll PluginA.cs。

新建控制台工程:IFTest 添加PluginInterface.dll到程序引用。

在bin\Debug里新建目录Plugins。

把PluginA.dll和PluginInterface.dll放到Plugins文件夹里。 

//主程序
using System;
using System.IO;
using System.Collections;
using System.Reflection;
 
namespace IFTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue q = new Queue();
            try
            {
                #region 获取插件列表
 
                string path = Environment.CurrentDirectory; 
                //string path = Application.StartupPath; --Windows From
                path = Path.Combine(path"Plugins");
                foreach (string file in Directory.GetFiles(path,"*.dll"))
                {
                    q.Enqueue(file);
                    Console.WriteLine(Path.GetFileName(file));
                }
 
                #endregion
 
                #region 加载插件及插件方法
 
                string asmFile = (string)q.Dequeue();
                string asmName = Path.GetFileNameWithoutExtension(asmFile);
                if (asmFile != string.Empty)
                {
                    Assembly asm = Assembly.LoadFrom(asmFile);
                    Type t = asm.GetType(asmName + "." + asmName); //GetType(Namespace.ClassName); 
                    PluginInterface.PluginInterface pr = (PluginInterface.PluginInterface)System.Activator.CreateInstance(t);
                    pr.printf();
                    Console.ReadKey();
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
            /*
              PluginA.dll
              PluginInterface.dll
              This is string for Plugin
             */
        }
    }
}

转载于:https://www.cnblogs.com/kknd1928/archive/2012/05/11/2495784.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值