一 、初识反射
反射:
反射主要使程序可以访问、检测、修改自身及其它应用程序的行为状态的一种方法。
反射常用之处;
动态加载DLL
动态创建类的实例
在程序中动态的访问程序集中的方法,使程序达到后期绑定的功能
二 、获取类型信息
#region 自定义类
public class testClass {
public string infoName;
public void testShow() { }
public int shuXing{get;set;}
}
#endregion
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region 打印出类的相关信息
Type tmp = typeof(testClass);
Response.Write("class name: "+tmp.Name+"
"); //类名 不带命名空间
Response.Write("class full name: " + tmp.FullName + "
"); //包含命名空间的类名
Response.Write("class namespace name: " + tmp.Namespace + "
");
Response.Write("class assembly name: " + tmp.Assembly + "
");
Response.Write("class module name: " + tmp.Module + "
");
Response.Write("class base type name: " + tmp.BaseType + "
");
Response.Write("class is class name: " + tmp.IsClass + "
");
Response.Write("
");
//遍历展示 类中的所有成员信息
MemberInfo[] memberTmpList = tmp.GetMembers();
foreach (var i in memberTmpList)
{
Response.Write(string.Format("{0}:{1}
",i.MemberType,i));
}
#endregion
}
}
三 、c# 反射调用一个类的方法
#region 自定义类
public class testClass {
public string infoName;
public void testShow() { }
public int shuXing{get;set;}
public string showThisTime(string t) {
return "反射调用这个方法__参数如下:"+t+" "+System.DateTime.Now.ToString("yyyyMMdd HH:mm:ss");
}
}
#endregion
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region 反射 调用方法
System.Reflection.Assembly tmpAssembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory+"bin\\所需反射类的.dll");
Type tmpType = tmpAssembly.GetType("bossManage.testClass");
object tmpO = System.Activator.CreateInstance(tmpType);
System.Reflection.MethodInfo tmpMethod = tmpType.GetMethod("showThisTime");
var tmpReturn = tmpMethod.Invoke(tmpO, new object[] { "传入参数" });
Response.Write(tmpReturn);
#endregion
}
}