C#插件式开发

  记录一下C#插件式开发。

  原理:主要模块【运行DLL(共享DLL)】、【界面主程序】、【插件DLL】

  原理没时间写太详细,以后有机会再补充吧,先上传代码。

以下是C#DLL程序集代码,命名为【Runtime】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Runtime
{
    public interface IAdd
    {
        int Add(int a, int b);
    }
}

以下是C#DLL程序集代码,命名为【Plugin】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Runtime;

namespace Plugin
{
    public class Operation : IAdd
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
}

以下是C#Console程序集代码,命名为为【Main】

using Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Main
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll");
            // 遍历所有的dll文件,可以自己规定插件名称(比如“*.plugin.dll” = "123.plugin.dll")  进行过滤
            foreach (string fn in files)
            {
                // 获取程序集
                Assembly ass = Assembly.LoadFrom(fn);
                // 获取所有类,但是此处并没有被实例化。
                foreach (Type pClass in ass.GetTypes())
                {
                    // 判断该类是否是实现了接口
                    if (pClass.GetInterface("IAdd") == (typeof(IAdd)))
                    {
                        // 创建实例类
                        object obj = ass.CreateInstance(pClass.FullName);
                        // 获取类方法
                        MethodInfo fun = pClass.GetMethod("Add");
                        // 执行类方法
                        object result = (int)fun.Invoke(obj, new object[] { 1, 30 });
                        Console.WriteLine(result);
                    }
                }
            }
            Console.ReadLine();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/smallshu/p/12536435.html