//Create By ChimHsiung;
//Begin 2016-10
//Last 2017-06
主界面窗体调用方法的设计变更历程:
一、原始方法,每个窗体一个类手动调用。弊端:一个系统动辄上百个类,代码量大不说,变更调整也不省事。
二、通过类名反射调用窗体,每个调用对象都设置好主类名及虚拟类名。主窗体调用时无须一个个类名写调用
,另外增加虚拟通用类设计
三、优化上一版本BUG,原因为DLL文件调用到其他非项目库时异常,改为手动指定DLL文件列表
四、最终版本 泛型反射调用 只为集中设计处理 /// <summary>
//Begin 2016-10
//Last 2017-06
主界面窗体调用方法的设计变更历程:
一、原始方法,每个窗体一个类手动调用。弊端:一个系统动辄上百个类,代码量大不说,变更调整也不省事。
switch (frmName)
{
case "frmNavigate":
frmNavigate fnav = new frmNavigate();
fnav.MdiParent = this;
fnav.Show();
break;
case "frmEmployee"://员工资料
frmEmployee femp = new frmEmployee();
femp.MdiParent = this;
femp.Show();
break;
case "frmModal"://模块管理
frmModal fmod = new frmModal();
fmod.MdiParent = this;
fmod.Show();
break;
case "frmField"://字段列管理
frmField ffld = new frmField();
ffld.MdiParent = this;
ffld.Show();
break;
default:
break;
}
二、通过类名反射调用窗体,每个调用对象都设置好主类名及虚拟类名。主窗体调用时无须一个个类名写调用
,另外增加虚拟通用类设计
//遍历全部DLL窗体
string dir = Directory.GetCurrentDirectory();
foreach (var file in Directory.GetFiles(dir + @"\", "*.dll"))
{
//排除Dev控件的DLL文件
FileInfo fi = new FileInfo(file);
if(fi.Name.Length>=10 && fi.Name.Substring(0, 10) == "DevExpress") continue;
//MessageBox.Show(file);
System.Reflection.Assembly a = System.Reflection.Assembly.LoadFile(file);
Type[] types = a.GetTypes();
foreach (Type t in types)
{
if (t.BaseType == typeof(frmBaseList))
{
if (t.Name == frmName)
{
var fbl = Activator.CreateInstance(t) as frmBaseList;
fbl.MdiParent = this;
fbl.Show();
//MessageBox.Show(file);
//MessageBox.Show(t.Name);
//Form fm = t.BaseType as Form;
}
}
}
}
三、优化上一版本BUG,原因为DLL文件调用到其他非项目库时异常,改为手动指定DLL文件列表
foreach(string file in SysParam.Sys_DllList)
{
System.Reflection.Assembly a = System.Reflection.Assembly.UnsafeLoadFrom(Directory.GetCurrentDirectory() + @"\" + file);
Type[] types = a.GetTypes();
foreach (Type t in types)
{
if (t.BaseType == typeof(Form))
{
if (t.Name == frmName)
{
try
{
var fbl = Activator.CreateInstance(t) as Form;
if (IsMdi)
fbl.MdiParent = this;
else
fbl.StartPosition = FormStartPosition.CenterScreen;
fbl.Text = frmText;
fbl.Show();
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
}
}
}
四、最终版本 泛型反射调用 只为集中设计处理
/// 泛型方法反射调用窗体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="frmName"></param>
/// <param name="frmType"></param>
/// <returns></returns>
public static T AssemblyForm<T>(string frmName)
{
try
{
string dir = Directory.GetCurrentDirectory();
foreach (string file in SysData.SysParam.Sys_DllList)
{
System.Reflection.Assembly a = System.Reflection.Assembly.UnsafeLoadFrom(Directory.GetCurrentDirectory() + @"\" + file);
Type[] types = a.GetTypes();
foreach (Type t in types)
{
if (t.BaseType == typeof(T))
{
if (t.Name == frmName)
{
//(typeof.MakeGenericType(T)
object fdl = Activator.CreateInstance(t);
return (T)fdl;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "调用窗体异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return default(T);
}