陶勇强—构建可扩展Windows窗体应用程序,界面窗体反射代码,程序集反射
<项目需求中的>首先创建以下程序集
1.CommonSnappbleTyoes.dll:改程序集包含将每个插件实现的类型定义,插件将会在可扩展的Windows窗体应用程序中引用.
2.CSharpSnapIn.dll:一个C#插件它使用CommonSnappbleTyoes.dll类型.
3.VBNetSnapIn.dll:一个用VB.NET编写的插件,它也同样使用CommonSnappbleTyoes.dll类型.
4.MyPluggableApp.exe:这个Windows窗体应用程序将成为可以被每个插件功能扩展的实体.另外,这个应用程序可以使用动态加载,反射和晚期绑定来动态获取预先不知道的程序集功能.
部分WINDOWS界面窗体代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using CommonSnappableTyies;
using System.IO;
namespace MyExtendableApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool LoadExternalModule(string path)
{
bool foundSnapIn = false;
IAppFunctionlity itfAppFx;
//动态加载中的程序集
Assembly asm = Assembly.LoadFrom(path);
Type[] type = asm.GetTypes();
for (int i = 0; i < type.Length; i++)
{
Type t = type[i].GetInterface("IAppFunctionlity");
if (t != null)
{
foundSnapIn = true;
//使用晚期绑定创建一个类型
object obj = asm.CreateInstance(type[i].FullName);
//脱离接口掉用接口的方法
itfAppFx = obj as IAppFunctionlity;
itfAppFx.DoIt();
this.listBox1.Items.Add(type[i].Name);
DisplyCommpanDate(type[i]);
}
}
return foundSnapIn;
}
//得到[CompanyInfo]数据
private void DisplyCommpanDate(Type t)
{
object[] obj = t.GetCustomAttributes(false);
foreach (CompanyInfoAttribute c in obj)
{
MessageBox.Show(c.Url,string.Format("Nore info about{0} can be foud at",c.Name));
}
}
private void snapInModuleToolStripMenuItem_Click(object sender, EventArgs e)
{
//允许用户加载一个程序集
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
if (LoadExternalModule(dlg.FileName) == false)
{
MessageBox.Show("没有实现接口的方法");
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
this.Time.Text = DateTime.Now.ToString();
}
//反射程序集调用方法
private void FanShe()
{
Assembly a ;
try
{
a = Assembly.Load("CommonSnappableTyies");
}
catch (FileNotFoundException e)
{
MessageBox.Show(e.ToString());
return;
}
Type b = a.GetType("CommonSnappableTyies.CompanyInfoAttribute");
object obj = Activator.CreateInstance(b);
MethodInfo mi = b.GetMethod("Show");
mi.Invoke(obj,null);
}
private void Form1_Load(object sender, EventArgs e)
{
this.FanShe();
}
}
}