1.在一個WINFORM中創建一個類html
namespace C03反射 { public class Dog { public string name; public int age; private bool gender; public string ShoutHi() { return this.name + "," + this.age + " , " + this.gender; } } }
使用的時候在主程序this
//1.獲取當前正在運行的 程序集(Assembly)對象 Assembly ass = this.GetType().Assembly;//獲取當前運行對象所屬的類所在的程序集對象 //2.獲取 程序集中的 Dog類的 類型(Type)對象 Type tDog = ass.GetType("C03反射.Dog");
Type[] tDogs = ass.GetTypes();//獲取全部的類型
//3.經過 程序集 獲取全部的 公共的(puclic) 類型
Type[] types = ass.GetExportedTypes();
注意這裏並非拿一個實例。編碼
//拿到全部的字段
FieldInfo[] fInfos = tDog.GetFields();
//3.獲取 Dog 類的 name 字段對象 FieldInfo fInfo = tDog.GetField("name");
MethodInfo[] mInfos = tDog.GetMethods();//獲取全部的方法
注意這裏他不只獲取到了咱們本身定義的方法,還把從基類OBJECT繼承下來的方法也顯示出來spa
這樣能夠獲取一個方法code
//1.根據 Dog的Type對象,實例化一個Dog對象 Dog d2 = Activator.CreateInstance(tDog) as Dog; Dog d3 = Activator.CreateInstance<Dog>();
注意:Activator.CreateInstance(tDog)這樣是一個Object類型,須要轉換下。第二個方法是硬編碼,把類型寫死了,用的相對少一點。htm
FieldInfo fInfo = tDog.GetField("name"); fInfo.SetValue(d2, "小白"); 這樣是爲一個字段賦值,賦值先後名字發生了改變。
MethodInfo mInfo = tDog.GetMethod("ShoutHi"); Dog d2 = Activator.CreateInstance(tDog) as Dog; string strRes = mInfo.Invoke(d2, null).ToString(); MessageBox.Show(strRes);
反射方式調用方法對象
根據路徑加載程序集blog
string strPath = @"M:\黑馬四期\2013-04-22 泛型反射\Code\C01泛型\libs\C01泛型.exe"; Assembly ass = Assembly.LoadFrom(strPath);