C#之插件

来源:互联网 发布:五子棋java程序代码 编辑:程序博客网 时间:2024/05/21 17:37

目标:开发一款支持插件的应用程序。

1.定义插件的基本框架,以后为该应用程序开发的插件都继承该框架。

项目:PluginFramework.dll

//IPlugin.csusing System;using System.Collections.Generic;using System.Text;namespace PluginFramework{    public interface IPlugin    {        void Load();    }}

2.插件开发

项目:MyPlugin.dll

添加引用:PluginFramework.dll

//MyPlugin.csusing System;using System.Collections.Generic;using System.Text;using PluginFramework;namespace MyPlugin{    public class MyPlugin : IPlugin    {        public void Load()        {            Console.WriteLine("Loading MyPlugin...");        }    }}

3.在应用程序中加载插件

项目:MyApplication.exe

添加引用:PluginFramework.dll

//Program.csusing System;using System.Collections.Generic;using System.Text;using System.Reflection;using PluginFramework;namespace MyApplication{    class Program    {        static void Main(string[] args)        {            Assembly assem = Assembly.LoadFrom("FirstPlugin.dll");            Type[] types = assem.GetTypes();            foreach (Type type in types)            {                if (type.GetInterface("IPlugin") != null)                {                    ((IPlugin)Activator.CreateInstance(type)).Load();                }            }            Console.ReadLine();        }    }}
原创粉丝点击