_01反射的用法
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Reflection; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace _01反射特性 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 15 16 //元数据:就是程序的方法,程序本事或程序集,文本信息 17 //发射 :在程序运行状态下 我们获得元数据的行为 反射用到的是type类 18 Console.WriteLine("*******获取发射对象********************"); 19 Class1 c = new Class1(); 20 Type t= c.GetType();//获取发射对象 21 Console.WriteLine(t); 22 23 Console.WriteLine("*****获取到所有的公有字段信息**********************"); 24 //通过发射对象获取到所有的公有字段信息 25 FieldInfo[] fid = t.GetFields();//写的时候先写命好的t.GetFields() 就可以知道返回的是什么 26 foreach (var item in fid) 27 { 28 Console.WriteLine(item); 29 } 30 Console.WriteLine("***************************"); 31 object obj= Activator.CreateInstance(t); 32 fid[0].SetValue(obj, 2); 33 fid[1].SetValue(obj, "夏"); 34 fid[2].SetValue(obj, '男'); 35 foreach (var item in fid) 36 { 37 Console.WriteLine(item.GetValue(obj)); 38 } 39 40 41 Console.WriteLine("********发射对象的类型。*******************"); 42 //拿到发射对象的类型。命名空间和程序集 43 Console.WriteLine(t.Name);//类的名字 44 Console.WriteLine(t.Namespace);//项目名称 45 Console.WriteLine(t.Assembly);//项目的信息 46 47 48 Console.WriteLine("*****拿到反射对象的所有方法GetMethods**********************"); 49 //拿到反射对象的所有方法GetMethods 50 MemberInfo[] me= t.GetMethods(); 51 foreach (var item in me) 52 { 53 Console.WriteLine(item); 54 } 55 56 Console.WriteLine("***********拿到非静态方法****************"); 57 //拿到非静态方法 58 MethodInfo mefo= t.GetMethod("test2");//t.GetMethod("test2");括号是方法名字 即使写了重载 名字也哟呵不一样 59 object obt = Activator.CreateInstance(t); 60 mefo.Invoke(obt, null);//Invoke(,)逗号前是创建实列对象的名字,逗号后是参数是否有 61 MethodInfo mee= t.GetMethod("test"); 62 mee.Invoke(obt, new object[] { "系哦啊王" }); 63 64 65 Console.WriteLine("*********拿到静态方法******************"); 66 //拿到静态方法 67 MethodInfo meth= t.GetMethod("test1"); 68 meth.Invoke(null, null); 69 MethodInfo metho= t.GetMethod("test3"); 70 metho.Invoke(null, new object[] { 12 }); 71 72 73 Console.WriteLine("********拿到程序集中的所有类型(类的名字)******************"); 74 Assembly ab= t.Assembly; 75 Type[] ta= ab.GetTypes(); 76 foreach (var item in ta) 77 { 78 Console.WriteLine(item); 79 } 80 } 81 } 82 }
1.上边的代码:是主函数的,下边的是它调用的类:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _01反射特性 8 { 9 class Class1 10 { 11 public int age; 12 public string name; 13 public char sex; 14 public int Age { get => age; set => age = value; } 15 public string Name { get => name; set => name = value; } 16 17 public void test2() 18 { 19 Console.WriteLine("test"); 20 } 21 public void test(string name) 22 { 23 Console.WriteLine("test "+ name); 24 } 25 public static void test1() 26 { 27 Console.WriteLine("test1"); 28 } 29 public static void test3(int age) 30 { 31 Console.WriteLine("test1+"+age); 32 } 33 } 34 }