PlugLoader 2017.7.3 Fix

    public class PlugLoader
    {
        private List<Assembly> pAssembly = new List<Assembly>();


        public Assembly LoaderDLL(string DllPath)
        {
            try
            {
                Assembly assembly = null;


                if (File.Exists(DllPath))
                {
                    List<Assembly> pSearch = pAssembly.Select((c) => { return (c.Modules.Count() > 0 ? c.Modules.ToList()[0].Name : "") == DllPath ? c : null; }).ToList();


                    if (pSearch.Count == 0)
                    {
                        assembly = Assembly.LoadFrom(DllPath);


                        pAssembly.Add(assembly);
                    }
                    else
                    {
                        assembly = pSearch.First();
                    }
                }


                return assembly;
            }
            catch
            {
                return null;
            }
        }


        public T LoadLibrary<T>(string DllPath) where T : class
        {
            Assembly assembly = LoaderDLL(DllPath);


            if (assembly == null)
                return null;


            Type type = null;


            Type pFindType = typeof(T);


            foreach (Type pType in assembly.GetTypes())
            {
                Boolean bInterface = pFindType.IsAssignableFrom(pType);
                if ((pType is T) || bInterface)
                {
                    type = pType;
                    break;
                }
            }


            if (type == null)
                return null;


            T tVar = assembly.CreateInstance(type.FullName) as T;


            return tVar;
        }
    }


附上測試代碼

    public interface IPlug
    {
        void ShowForm();
    }

    public partial class Form1 : Form, IPlug
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void ShowForm()
        {
            this.ShowDialog();
        }
    }

            PlugLoader pLoader = new PlugLoader();

            IPlug pPlug = pLoader.LoadLibrary<IPlug>("TestLib.dll");
            //pPlug.ShowForm();

            IPlug pPlug1 = pLoader.LoadLibrary<IPlug>("TestLib.dll");
            pPlug1.ShowForm();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章