反射是一个很强大的功能,不过好像有些消耗性能,你们慎重使用。数组
1.反射是干什么的?ide
经过反射,咱们可与获取程序集中的原数据。函数
1.什么是程序集?性能
dll、exe 这些将不少能实现具体功能的代码封装起来的文件(我本身的理解,可能不对!)。this
2.用到的状况有哪些?spa
编译器的提示功能、反编译、还有调用别人的dll时,其它我不知道的。。code
3.下面直接奉上一个实例的代码,供参考。对象
(1)先建一个叫作Common的类库,在里面建一个叫Person的类,类的代码以下。blog
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Common { public class Person { //姓名 private string _name; public string Name { get { return _name; } set { _name = value; } } //年龄 private int _age; public int Age { get { return _age; } set { _age = value; } } //打印姓名和年龄 public void printfNameAge() { Console.WriteLine(_name); Console.WriteLine(_age); } //有参数的构造函数 public Person(string name, int age) { this.Name = name; this.Age = age; } } }
(2)在建一个窗体程序,其中的Program.cs代买以下,里面实现了一些反射的经常使用方法。get
在运行这个程序以前,你要将Common编译一下,而后去Debug中将Common.dll拷贝到你建好程序的Debug中。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection;//反射 //Author 崔时雨 //Date 20160808 namespace 反射 { class Program { static void Main(string[] args) { //1.加载程序集文件 string path = AppDomain.CurrentDomain.BaseDirectory + "Common.dll"; Assembly ass = Assembly.LoadFile(path); //2. 获取数据集数据的三个函数 //2.1 获取指定对象的类型 Type t = ass.GetType("Common.Person"); Console.WriteLine(t.Name); //2.2 获取元数据,不管公有私有。 Type[] type1 = ass.GetTypes(); Console.WriteLine("打印2.2 获取元数据,不管公有私有。"); foreach (Type item in type1) { Console.WriteLine(item.Name); Console.WriteLine(item.FullName); Console.WriteLine(item.Namespace); } //2.3 值获取公有的 Type[] type2 = ass.GetExportedTypes(); Console.WriteLine("\n打印2.3 值获取公有的"); foreach (Type item in type2) { Console.WriteLine(item.Name); Console.WriteLine(item.FullName); Console.WriteLine(item.Namespace); } //3 建立对象 //3.1调用person中的默认无参的构造函数 // object obj1 = ass.CreateInstance("Common.Person");//一般不用这种,若是存在有参数的构造函数,不能建立。 //3.2 能够构造函数有参数的对象 object obj2 = Activator.CreateInstance(t/*对象类型*/, "小明", 18); //3.2.1得到数据源的属性数组 PropertyInfo[] strPro = obj2.GetType().GetProperties(); Console.WriteLine("\n打印3.2.1得到数据源的属性数组"); foreach (PropertyInfo item in strPro) { Console.WriteLine(item.Name); } //3.2.2得到数据源的方法数组 MethodInfo[] methods = obj2.GetType().GetMethods(); Console.WriteLine("\n打印3.2.2得到数据源的方法数组 "); foreach (MethodInfo item in methods) { Console.WriteLine(item.Name); } //3.3调用函数,打印。 MethodInfo md = obj2.GetType().GetMethod("printfNameAge"); Console.WriteLine("\n调用 Person中的printfNameAge方法,打印 姓名和年龄"); md.Invoke(obj2,null); Console.ReadKey(); } } }
4.运行结果
总结:
参考了不少人的博客,发现要想弄清楚反射还须要许多其它的知识,使用这篇内容的知识,已经能够简单的使用反射了。
知识点总要一个一个学,积累的多了,就会连成串。