反射:System.Reflection .Net框架提供帮助类库 ,可以动态读取并使用metadata
Assembly assembly = Assembly.Load("Test");//dll名称 从当前目录加载 Assembly assembly1 = Assembly.LoadFrom("Test.dll");//带后缀或完整名称 Assembly assembly2 = Assembly.LoadFile(@"D:Test.dll");//完整路径的加载
Assembly assembly = Assembly.Load("");//加载dll Type type = assembly.GetType("");//获取类型信息 object ob = Activator.CreateInstance(type);//创建对象
People people = new People(); Type typePeople = typeof(People); Type typePeopleDTO = typeof(PeopleDTO); people.ID = Guid.NewGuid(); people.Name = "测试"; people.Age = 3; object peopleDTO = Activator.CreateInstance(typePeopleDTO); foreach (var prop in typePeopleDTO.GetProperties()) { object value = typePeople.GetProperty(prop.Name).GetValue(people); prop.SetValue(peopleDTO, value); } foreach (var field in typePeopleDTO.GetFields()) { object value = typePeople.GetField(field.Name).GetValue(people); field.SetValue(peopleDTO, value); }
反射可以破坏单例,调用私有方法
典型:MVC就是通过反射调用方法
反射的优缺点:
优点:动态
缺点:1.写起来复杂;
2.避开编译器的检查
3.性能问题