//定义主程序插件接口
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
             */
        }
    }
}
posted on 2012-05-11 12:32  KKND1928  阅读(213)  评论(0编辑  收藏  举报