首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

反射學習系列 3-反射實例應用 (四) 外掛架構宿主實現

     編輯:關於C語言

宿主介面與實現


public class Host : IHost
{
    private List plugins = new List();
    public List Plugins => plugins;

    public int LoadPlugins(string path)
    {
        string[] files = Directory.GetFiles(path, "*.dll");
        foreach (var file in files)
        {
            Assembly asm = Assembly.LoadFrom(file);
            foreach (var type in asm.GetExportedTypes())
            {
                if (type.IsClass && typeof(ILog).IsAssignableFrom(type))
                {
                    ILog plugin = Activator.CreateInstance(type) as ILog;
                    plugins.Add(plugin);
                }
            }
        }
        return plugins.Count;
    }

    public ILog GetLog(string name)
    {
        foreach (var item in plugins)
            if (item.GetType().ToString() == name) return item;
        return null;
    }
}

主程式使用


static void Main()
{
    Host host = new Host();
    host.LoadPlugins(".");
    ILog log = host.GetLog(ConfigurationManager.AppSettings["LogType"]);
    log.Write(new Exception("異常測試"));
}

ILog 實作參考前文。此架構展示反射動態載入組件、掃描型別、篩選實作特定介面的類別、實例化並管理外掛的完整流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved