最近项目上使用到到反射,找到以前保留的一份文档,作者是李志伟,找不到原出处,在此表示感谢。
在这分享一下。
审查元数据并收集关于它的类型信息的能力称为反射。元数据(编译以后的最基本数据单元)就是一大堆的表,当编译程序集或者模块时,编译器会创建一个类定义表,一个字段定义表,和一个方法定义表等。System.reflection命名空间包含的几个类,允许用户解析这些元数据表的代码:
System.Reflection.Assembly:表示一个程序集。
System.Reflection.Module:在模块上执行反射。
System.Type:表示各种类型。
System.Reflection.MethodBase:提供有关方法和构造函数的信息。
System.Reflection.MethodInfo:发现方法的属性并提供对方法元数据的访问。
System.Reflection.MemberInfo:获取或访问有关成员属性。
System.Reflection.FieldInfo:发现字段属性并提供对字段元数据的访问权。
System.Reflection.PRopertyInfo:发现或访问属性(Property)的属性(Attribute)。
System.Reflection.EventInfo:发现事件的属性并提供对事件元数据的访问权。
System.Reflection.ConstructorInfo:发现或访问类构造函数的属性。
classProgram
{
staticvoidMain(string[] args)
{
Assemblyassem =Assembly.Load("mscorlib");//加载系统程序集
PrintInfo(assem);//输出程序集相关信息
assem =Assembly.LoadFrom(@"F:/System.Data.SQLite.dll");//或使用LoadFile()方法
PrintInfo(assem);//输出程序集相关信息
assem =Assembly.GetExecutingAssembly();//获取当前执行代码的程序集
PrintInfo(assem);//输出程序集相关信息
Console.Read();
}
//输出程序集相关信息
staticvoidPrintInfo(Assemblyassem)
{
Console.WriteLine("程序集全名:"+ assem.FullName);
Console.WriteLine("程序集的版本:"+ assem.GetName().Version);
Console.WriteLine("程序集初始位置:"+ assem.CodeBase);
Console.WriteLine("程序集位置:"+ assem.Location);
Console.WriteLine("程序集入口:"+ assem.EntryPoint);
Type[] types = assem.GetTypes();//得到该程序集里所有的类型
Console.WriteLine("程序集下包含的类型数:"+ types.Length);
//foreach (var item in types)
//{
// Console.WriteLine("类:" + item.Name);//输出类型名
//}
Console.WriteLine("============================/n");
}
}
新闻热点
疑难解答