c#中反射(Reflection)的作用
在软件开发中(C#),通常会调用程序集,及dll文件,在.net中是这样称的,通常也可以叫做动态连接库文件,大多数.net程序员都会将一个模块编码完成并生成功,但是在调用的时候功能组件都来引用的话,这样就麻烦多了,因此我们使用反射功能来实现功能组建调用using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
namespace HR.Win
{
/// <summary>
/// 反射调用功能组件
/// </summary>
public class ReflectionFunction
{
/// <summary>
/// 反射调用Mdi窗体
/// </summary>
/// <param name="FunctionAssemblyFileName">功能程序集文件名称</param>
/// <param name="AssemblyNamespaceAndClass">[功能程序集命名空间].[类名(窗体名)]</param>
/// <param name="MdiParentForm">Mdi父窗体</param>
/// <param name="functionParameter">功能模块传递参数组件HR.Win.FunctionParameter</param>
/// <returns></returns>
public Form LoadMdiForm(string FunctionAssemblyFileName, string AssemblyNamespaceAndClass, Form MdiParentForm, HR.Win.FunctionParameter functionParameter)
{
return LoadForm(FunctionAssemblyFileName, AssemblyNamespaceAndClass, MdiParentForm, functionParameter);
}
/// <summary>
/// 反射调用模式Dialog窗体
/// </summary>
/// <param name="FunctionAssemblyFileName">功能程序集文件名称</param>
/// <param name="AssemblyNamespaceAndClass">[功能程序集命名空间].[类名(窗体名)]</param>
/// <param name="functionParameter">功能模块传递参数组件HR.Win.FunctionParameter</param>
/// <returns></returns>
public Form LoadDialogForm(string FunctionAssemblyFileName, string AssemblyNamespaceAndClass, HR.Win.FunctionParameter functionParameter)
{
return LoadForm(FunctionAssemblyFileName, AssemblyNamespaceAndClass, null, functionParameter);
}
/// <summary>
/// 反射调用Mdi窗体
/// </summary>
/// <param name="FunctionAssemblyFileName">功能程序集文件名称</param>
/// <param name="AssemblyNamespaceAndClass">[功能程序集命名空间].[类名(窗体名)]</param>
/// <param name="MdiParentForm">Mdi父窗体</param>
/// <param name="functionParameter">功能模块传递参数组件HR.Win.FunctionParameter</param>
/// <returns></returns>
private Form LoadForm(string FunctionAssemblyFileName, string AssemblyNamespaceAndClass, Form MdiParentForm, HR.Win.FunctionParameter functionParameter)//HR.Win.FunctionParameter这个是我事先写的一个功能参数传递的组件,
{
string AssemblyFilePath = Application.StartupPath + "\\" + FunctionAssemblyFileName;
if (File.Exists(AssemblyFilePath) == true)
{
System.Reflection.Assembly assembly = Assembly.LoadFile(AssemblyFilePath);
Type FormType = assembly.GetType(AssemblyNamespaceAndClass, true, true);
Form frm = FormType.InvokeMember(null,
System.Reflection.BindingFlags.DeclaredOnly
| System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.CreateInstance,
null, null, null) as Form; //这句相当关键,他就实现反射
frm.Tag = functionParameter;
if (MdiParentForm == null)
{
frm.ShowDialog();
}
else
{
frm.MdiParent = MdiParentForm;//如果是Mdi窗体就用frm.MdiParent
frm.Show();
}
if (frm.MaximizeBox == true)
{
frm.WindowState = FormWindowState.Maximized;
}
return frm;
}
return null;
}
}
}
通过这个组件,我们就可以很轻松的实现反射功能调用组件
页:
[1]