C#中的反射(System.Reflection)
一、獲取程序集Assembly
1、獲取當(dāng)前運(yùn)行的程序集
System.Reflection.Assembly[] asm = AppDomain.CurrentDomain.GetAssemblies(); // Assembly b = Assembly.GetExecutingAssembly();
2、獲取指定文件的程序集:Load,LoadFrom,LoadFile方法。
Assembly c = Assembly.Load("mscorlib.dll");//如果你引用了程序及,那么就直接Load()方法,參數(shù)里面程序集名稱就可以加載了。Assembly c = Assembly.Load("mscorlib"); Assembly d = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll");//LoadFrom只能用于加載不同標(biāo)識(shí)的程序集, 也就是唯一的程序集, 不能用于加載標(biāo)識(shí)相同但路徑不同的程序集。 Assembly e = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "mscorlib.dll");//LoadFile:只加載指定文件,但不會(huì)自動(dòng)加載依賴程序集
二、獲取類型Type (指Class類):
Assembly asm = Assembly.GetExecutingAssembly(); Type[] tArr = asm.GetExportedTypes();//獲取程序集中定義的公共類型
1、從類字符串中獲得Type對(duì)象:Assembly.GetType(“”),Module.GetType(“”), Type.GetType(“”)
Assembly ass = Assembly.LoadFrom(@"C:\bin\Debug\ConsoleApplication2.exe"); Console.WriteLine(ass.GetType("ConsoleApplication2.Person").ToString()); //根據(jù)程序集(dll或exe)獲取里面的Class Module mod = ass.GetModules()[0]; Console.WriteLine(mod.GetType("ConsoleApplication2.Person").ToString()); Type type = Type.GetType("System.Int32");//靜態(tài)方法,參數(shù)為完全限定名(首選) Type type = Type.GetType("MyAssembly.Example",false,true) //注意0是類名,參數(shù)1表示若找不到對(duì)應(yīng)類時(shí)是否拋出異常,參數(shù)2表示類名是否區(qū)分大小寫
2、從具體類中獲得Type對(duì)象:typeof運(yùn)算符
Type t4 = typeof(TestSpace.TestClass);//使用typeof運(yùn)算符
3、從實(shí)例中獲得Type對(duì)象:Object.GetType()
Example example = new Example(); Type type = example.GetType(); Type t3 = 42.GetType();//根據(jù)對(duì)象實(shí)例獲取類型
4、Type的屬性
t.IsPublic; t.IsAbstract; t.IsClass; t.IsValueType;
三、獲取成員MemberInfo
MemberInfo[] miArr = t.GetMembers(BindingFlags.Instance | BindingFlags.Public);//實(shí)例與公共成員。還有BindingFlags.Static|BindingFlags.NonPublic foreach (MemberInfo item in miArr) { bool a = item is FieldInfo; PropertyInfo; MethodBase; ConstructorInfo; MethodInfo; EventInfo; Type; } t.GetConstructor();//獲取構(gòu)造函數(shù) t.GetFields();//獲取字段 t.GetProperties(); //獲取屬性 t.GetMethods();//獲取方法 t.GetEvents();//獲取事件 t.GetInterfaces();//獲取接口 t.GetCustomAttributes(true);//獲取類型上標(biāo)記的自定義屬性
在System.Reflection命名空間內(nèi)包含多個(gè)反射常用的類:
- Assembly: 通過(guò)此類可以加載操縱一個(gè)程序集,并獲取程序集內(nèi)部信息
- EventInfo: 該類保存給定的事件信息
- FieldInfo :該類保存給定的字段信息
- MethodInfo :該類保存給定的方法信息
- MemberInfo :該類是一個(gè)基類,它定義了EventInfo、FieldInfo、MethodInfo、PropertyInfo的多個(gè)公用行為
- Module :該類可以使你能訪問(wèn)多個(gè)程序集中的給定模塊
- ParameterInfo :該類保存給定的參數(shù)信息
- PropertyInfo: 該類保存給定的屬性信息
四、獲取具體成員
Type t = Assembly.GetExecutingAssembly().GetType("TestSpace.TestClass"); MethodInfo m = t.GetMethod("TestMethod"); ParameterInfo[] p = m.GetParameters();//獲取方法參數(shù)
五、創(chuàng)建實(shí)例
1、根據(jù)Assembly創(chuàng)建類型實(shí)例:asm.CreateInstance()
Assembly asm = Assembly.GetExecutingAssembly(); TestClass obj = asm.CreateInstance("TestSpace.TestClass");//根據(jù)Assembly創(chuàng)建類型實(shí)例
2、根據(jù)類型創(chuàng)建實(shí)例:Activator.CreateInstance()
Type t = Type.GetType("TestSpace.TestClass"); TestClass obj = (TestClass)Activator.CreateInstance(t);//1、根據(jù)類型創(chuàng)建實(shí)例 TestClass obj = (TestClass)Activator.CreateInstance(t, new object[] { "aa" });// 2、根據(jù)”有參數(shù)的構(gòu)造函數(shù)”創(chuàng)建實(shí)例 // TestClass obj = (TestClass)t.InvokeMember("TestClass", BindingFlags.CreateInstance, null, null, null);
六、調(diào)用方法
1、調(diào)用實(shí)例方法:Invoke
MethodInfo m = t.GetMethod("WriteString"); object returnValue = m.Invoke(obj, new object[] { "test", 1 });//傳兩參數(shù),若方法無(wú)參數(shù),可以將Invoke的第二個(gè)參數(shù)設(shè)為null //或者 object returnValue = m.Invoke(obj, BindingFlags.Public, Type.DefaultBinder, new object[] { "test", 1 }, null);//最后一個(gè)參數(shù)表示Culture.
2、調(diào)用靜態(tài)方法
MethodInfo m = t.GetMethod("StaticMethod"); object returnValue = m.Invoke(null, new object[] { "test", 1 });
七、反射屬性
通過(guò)System.Reflection.Property能查找到類里面的屬性?!〕S玫姆椒ㄓ蠫etValue(object,object[])獲取屬性值和SetValue(object,object,object[])設(shè)置屬性值
PropertyInfo propertyName = type.GetProperty("Name"); //獲取Name屬性對(duì)象 propertyName.SetValue(obj, "張飛", null); //設(shè)置Name屬性的值 object objName = propertyName.GetValue(obj, null); //獲取屬性值
根據(jù)屬性的類型設(shè)置屬性的值
Type type = typeof(Person); //注意要輸入全部路徑,包括命名空間 object obj = Activator.CreateInstance(type); //假設(shè)這是存在于XML的數(shù)據(jù) Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("Id", "1"); dic.Add("Name", "神靈武士"); dic.Add("Birthday", "2001-01-01"); PropertyInfo[] ProArr = type.GetProperties(); foreach (PropertyInfo p in ProArr) { if (dic.Keys.Contains(p.Name)) { p.SetValue(obj, Convert.ChangeType(dic[p.Name], p.PropertyType), null); //當(dāng)需要給屬性設(shè)置不同類型的值時(shí) } } Person person = obj as Person; Console.WriteLine(person.Birthday);
八、反射特性
通過(guò)System.Reflection.MemberInfo的GetCustomAttributes(Type,bool)就可反射出一個(gè)類里面的特性。
Assembly assembly = Assembly.Load("fanshe"); Type type = assembly.GetType("fanshe.Person"); //注意要輸入全部路徑,包括命名空間 object obj = Activator.CreateInstance(type); object[] typeAttributes = type.GetCustomAttributes(false); //獲取Person類的特性 foreach (object attribute in typeAttributes) { Console.WriteLine(attribute.ToString()); //輸出 System.SerializableAttribute 因?yàn)槲以赑erson上里加了個(gè)[Serializable] }
九、創(chuàng)建委托實(shí)例
TestDelegate myDelegate = (TestDelegate)Delegate.CreateDelegate(typeof(TestDelete), obj, "MyMethod"); string returnValue = myDelegate("Hello");//執(zhí)行委托
十、應(yīng)用舉例
1、動(dòng)態(tài)加載程序集
Assembly asm = Assembly.LoadFrom(@"E:\Test.dll"); Type type = asm.GetType("TestSpace.TestClass"); object obj = System.Activator.CreateInstance(type);//也可以使用強(qiáng)制轉(zhuǎn)換,將obj轉(zhuǎn)換為預(yù)定義的接口或者抽象類(如Form),直接執(zhí)行基方法,不用反射GetMethod . MethodInfo m = type.GetMethod("WriteString"); m.Invoke(obj, new object[] { "test" });
2、獲得List<T>中的T類型:
List<Dog> dogs = new List<Dog>(); Type type = dogs.GetType(); if (type.IsGenericType) { Type[] genericArgTypes = type.GetGenericArguments(); if (genericArgTypes[0] == typeof(Dog)) { //你想要判斷的是這個(gè)嗎? } }
到此這篇關(guān)于C#反射(Reflection)的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章

基于C#實(shí)現(xiàn)的輕量級(jí)多線程隊(duì)列圖文詳解

關(guān)于C#結(jié)構(gòu)體 你需要知道的

C#高級(jí)靜態(tài)語(yǔ)言效率利器之泛型詳解

WinForm實(shí)現(xiàn)自定義右下角提示效果的方法