c# 簡單實現 外掛程式模型 反射方式

來源:互聯網
上載者:User

標籤:

利用反射方式實現外掛程式模型,wpf控制項作為外掛程式,然後用另外的表單載入。

首先定義外掛程式介面:

    public interface IUserControlLevel1    {        string PluginName { get; set; }        int PluginIndex { get; set; }    }

 

userControl繼承定義的介面:

    /// <summary>    /// UserControl1.xaml 的互動邏輯    /// </summary>    public partial class UserControl1 : UserControl, IUserControlLevel1    {        public UserControl1()        {            InitializeComponent();        }        public string PluginName        {            get;            set;        }        public int PluginIndex        {            get;            set;        }    }

 

 

管理類裡定義尋找外掛程式,並返回結果。

主要代碼如下:

   public static List<IUserControlLevel1> GetUserControlLevel1(string directoryPath)        {            List<IUserControlLevel1> li = new List<IUserControlLevel1>();            string[] files = Directory.GetFiles(directoryPath, "*.dll");            foreach (var file in files)            {                Assembly assembly = Assembly.LoadFrom(file);//載入控制項                Type[] types = assembly.GetTypes();//載入所有類型                foreach (var type in types)                {                    if (!type.IsClass || type.IsNotPublic)                    {                        continue;                    }                    Type[] interfaces = type.GetInterfaces();//載入該類型介面                    if (interfaces.Contains(typeof(IUserControlLevel1)))                    {                        object obj = Activator.CreateInstance(type);                        IUserControlLevel1 uc = (IUserControlLevel1)obj;                        Object obj2 = type.InvokeMember(type.FullName,BindingFlags.CreateInstance, null, null, null);                        IUserControlLevel1 uc2 = (IUserControlLevel1)obj2;                        li.Add(uc2);                        continue;                    }                }            }            return li;        }

 

然後主表單可以尋找預設路徑下的外掛程式 並載入到介面。

源碼如下:

http://files.cnblogs.com/files/lizhijian/%E6%8F%92%E4%BB%B6%E6%A8%A1%E5%9E%8B.rar

c# 簡單實現 外掛程式模型 反射方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.