反射可以读取程序集中代码的内容,程序集一般指(dll或exe文件)。
反射中Type类,这个类太强大了,可以获取到另一个类的名称,命名空间,程序集,以及这个类中的字段,属性,方法。可以方便我们查看某个类的方法,属性,字段。
public void Test1() { Person per = new Person(); Type TypeObj = per.GetType(); Console.WriteLine(TypeObj.Name); //反射类的名称 Console.WriteLine(TypeObj.Namespace); //反射类的命名空间 Console.WriteLine(TypeObj.Assembly); //反射类所在的程序集 Console.WriteLine(TypeObj.IsPublic); //反射类是否为公共 Console.WriteLine(TypeObj.IsSealed); //反射类是否密封 } public void Test2() { Person per = new Person(); Type TypeObj = per.GetType(); FieldInfo[] infor = TypeObj.GetFields(); //获取类中的字段 foreach (FieldInfo item in infor) { Console.WriteLine(item.Name); } Console.WriteLine("--------------"); MethodInfo[] MeFor = TypeObj.GetMethods(); //获取类中的方法 foreach (MethodInfo item in MeFor) { Console.WriteLine(item.Name); } Console.WriteLine("--------------"); PropertyInfo[] ProFor = TypeObj.GetProperties(); //获取类中的属性 foreach (PropertyInfo item in ProFor) { Console.WriteLine(item.Name); } Console.WriteLine("--------------"); }
一些运行技巧:Console.ReadLine()作用
从控制台中读取用户输入的一行字符串,很多人添加ReadLine()是为了让程序运行完了停下来,避免控制台窗口被关掉。
Assembly获取类的方法
public void Test1() { Person per = new Person(); //得到程序集 Assembly ass = per.GetType().Assembly; Console.WriteLine(ass.FullName); //通过程序集得到所有的类 Type[] typArray = ass.GetTypes(); foreach (Type item in typArray) { Console.WriteLine(item.Name); } } public void Test2() { Assembly assObj = Assembly.LoadFrom(@""); //通过程序集得到所有的类 Type[] typArray = assObj.GetTypes(); foreach (Type item in typArray) { Console.WriteLine(item.Name); } }