標籤:
利用反射方式實現外掛程式模型,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# 簡單實現 外掛程式模型 反射方式