最近項目上使用到到反射,找到以前保留的一份文檔,作者是李志偉,找不到原出處,在此表示感謝。
在這分享一下。
審查元數(shù)據(jù)并收集關(guān)于它的類型信息的能力稱為反射。元數(shù)據(jù)(編譯以后的最基本數(shù)據(jù)單元)就是一大堆的表,當(dāng)編譯程序集或者模塊時,編譯器會創(chuàng)建一個類定義表,一個字段定義表,和一個方法定義表等。System.reflection命名空間包含的幾個類,允許用戶解析這些元數(shù)據(jù)表的代碼:
System.Reflection.Assembly:表示一個程序集。
System.Reflection.Module:在模塊上執(zhí)行反射。
System.Type:表示各種類型。
System.Reflection.MethodBase:提供有關(guān)方法和構(gòu)造函數(shù)的信息。
System.Reflection.MethodInfo:發(fā)現(xiàn)方法的屬性并提供對方法元數(shù)據(jù)的訪問。
System.Reflection.MemberInfo:獲取或訪問有關(guān)成員屬性。
System.Reflection.FieldInfo:發(fā)現(xiàn)字段屬性并提供對字段元數(shù)據(jù)的訪問權(quán)。
System.Reflection.PRopertyInfo:發(fā)現(xiàn)或訪問屬性(Property)的屬性(Attribute)。
System.Reflection.EventInfo:發(fā)現(xiàn)事件的屬性并提供對事件元數(shù)據(jù)的訪問權(quán)。
System.Reflection.ConstructorInfo:發(fā)現(xiàn)或訪問類構(gòu)造函數(shù)的屬性。

classProgram
{
staticvoidMain(string[] args)
{
Assemblyassem =Assembly.Load("mscorlib");//加載系統(tǒng)程序集
PrintInfo(assem);//輸出程序集相關(guān)信息
assem =Assembly.LoadFrom(@"F:/System.Data.SQLite.dll");//或使用LoadFile()方法
PrintInfo(assem);//輸出程序集相關(guān)信息
assem =Assembly.GetExecutingAssembly();//獲取當(dāng)前執(zhí)行代碼的程序集
PrintInfo(assem);//輸出程序集相關(guān)信息
Console.Read();
}
//輸出程序集相關(guān)信息
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("程序集下包含的類型數(shù):"+ types.Length);
//foreach (var item in types)
//{
// Console.WriteLine("類:" + item.Name);//輸出類型名
//}
Console.WriteLine("============================/n");
}
}
新聞熱點
疑難解答