日期:2014-05-17  浏览次数:20741 次

C#利用反射开发插件

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using PluginsAdd;

namespace MyNotePadPlus
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            //检查plugins目录下是否有DLL文件
            //获取当前执行的exe文件的绝对路径
            string exepath = Assembly.GetExecutingAssembly().Location;
            //获取了插件的目录路径
            string pluginspath = Path.Combine(Path.GetDirectoryName(exepath), "plugins");


            //搜索pluginspath目录下是否有对应的dll文件
            //返回值是一个string数组,里面存储着每个dll文件的完整路径
            string[] dlls = Directory.GetFiles(pluginspath, "*.dll");

            //循环遍历把每个插件(dll)都加载起来。
            foreach (string item in dlls)
            {
                Assembly assem = Assembly.LoadFile(item);

                //获取所有的public类型
                Type[] types = assem.GetExportedTypes();

                //获得接口的Type
                Type typeIEditor = typeof(IEditor);
                //遍历每个类型看看这个类型是否是实现了IEditor接口的类型
                foreach (Type typeClass in types)
                {
                    //判断当前类型typeClass,是否实现了IEditor这个接口。
   &n