C#插件式开发

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#插件式开发

ゞ七情   2020-03-21 我要评论

  记录一下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();
        }
    }
}

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们