反射-学习笔记3

1. 反射字段属性,获取和赋值
2. 封装数据库访问层   Console.WriteLine("*********************动态获取属性和字段************************");

  {
People people
= new People() { Id = 506, Name = "YoYo" }; people.Description = "VIP学员"; Type type = typeof(People); foreach (PropertyInfo item in type.GetProperties ()) { object oValue=item.GetValue(people); Console.WriteLine("{0}: {1}", item.Name, oValue); } foreach (FieldInfo item in type.GetFields ()) { object oValue = item.GetValue(people); Console.WriteLine("{0}: {1}", item.Name, oValue); } } { Console.WriteLine("*********************设置属性和字段的值************************"); Type type = typeof(People); object oPeople = Activator.CreateInstance(type); foreach (PropertyInfo item in type.GetProperties()) { Console.WriteLine("{0}: {1}", item.Name, item.GetValue (oPeople ));//为0 if(item .Name .Equals ("Id")) { item.SetValue(oPeople, 505); } else { item.SetValue(oPeople, "DoDo"); } Console.WriteLine("{0}: {1}", item.Name, item.GetValue(oPeople));//设置后的值 } foreach (FieldInfo item in type.GetFields()) { Console.WriteLine("{0}: {1}", item.Name, item.GetValue(oPeople));//为null item.SetValue(oPeople, "VIP学员"); Console.WriteLine("{0}: {1}", item.Name, item.GetValue(oPeople));//设置后的值 } }

 

posted @ 2016-11-29 14:33  HepburnXiao  阅读(117)  评论(0编辑  收藏  举报