public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* Example 3 UI*/
Type[] typePublic = null; Type typeIExecute = null;
string exeDirPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //得到运行目录
string[] dellPaths = Directory.GetFiles(exeDirPath, "*.dll");//得到所有的DLL
for (int i = 0; i < dellPaths.Length; i++)
{
Assembly asm = Assembly.LoadFile(dellPaths[i]);
//Assembly asm = Assembly.LoadFrom("ClassLibrary1.dll");
typePublic = asm.GetExportedTypes();//得到所有的public方法
typeIExecute = typeof(IExecute);//接口的类型
for (int j = 0; j < typePublic.Length; j++)
{
if (typeIExecute.IsAssignableFrom(typePublic[j]) && !typePublic[j].IsAbstract)//实现了IExecute,且非抽象类
{
IExecute execut = (IExecute)Activator.CreateInstance(typePublic[j]);
ToolStripItem tsoitem = menuStrip1.Items.Add(execut.ExeName);//增加到菜单
tsoitem.Click += new EventHandler(tsoitem_Click);//添加点击事件
tsoitem.Tag = execut;//将namespace.class记录在新增控件的tag属性中
}
}
}
}
void tsoitem_Click(object sender, EventArgs e)
{
IExecute execut = (IExecute)((ToolStripItem)sender).Tag;
execut.Execute();
}
{
public Form1()
{
InitializeComponent();
/* Example 3 UI*/
Type[] typePublic = null; Type typeIExecute = null;
string exeDirPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //得到运行目录
string[] dellPaths = Directory.GetFiles(exeDirPath, "*.dll");//得到所有的DLL
for (int i = 0; i < dellPaths.Length; i++)
{
Assembly asm = Assembly.LoadFile(dellPaths[i]);
//Assembly asm = Assembly.LoadFrom("ClassLibrary1.dll");
typePublic = asm.GetExportedTypes();//得到所有的public方法
typeIExecute = typeof(IExecute);//接口的类型
for (int j = 0; j < typePublic.Length; j++)
{
if (typeIExecute.IsAssignableFrom(typePublic[j]) && !typePublic[j].IsAbstract)//实现了IExecute,且非抽象类
{
IExecute execut = (IExecute)Activator.CreateInstance(typePublic[j]);
ToolStripItem tsoitem = menuStrip1.Items.Add(execut.ExeName);//增加到菜单
tsoitem.Click += new EventHandler(tsoitem_Click);//添加点击事件
tsoitem.Tag = execut;//将namespace.class记录在新增控件的tag属性中
}
}
}
}
void tsoitem_Click(object sender, EventArgs e)
{
IExecute execut = (IExecute)((ToolStripItem)sender).Tag;
execut.Execute();
}
}
public interface IExecute
{
string ExeName
{
get;
set;
}
///<summary>
///执行的方法
///</summary>
void Execute();
}
public class One:IExecute
{
public One()
{
ExeName = "MenuOne";
}
public string ExeName
{
get;
set;
}
public void Execute()
{
MessageBox.Show("Execute One");
}
}