在这里我们假设这样一个场景:在一个三层bs系统(asp.net)中有一个实体类Student,包括Name,Age两个字段。现在需要把 这个实体类的数据显示在一个StudentInfo.aspx页面上,StudentInfo.aspx中有两个文本框:StudentName(用来显示Student.Name) StudentAge(用来显示Student.Age). 下面的步骤将通过反射和Attribute来实现自动把Student实体显示在StudentInfo中: 1,首先,先需要实现一个Attribute用来表明实体类中的字段与界面中的控件的对应关系。 using System; using System.Reflection public class ControlIDAttribute:Attribute { public string ID;
public ControlIDAttribute(string id) { ID=id; } } 2,然后,需要在实体类中给字段绑上ControlID using System; public class Student { [ControlID("StudentName")] public string name; [ControlID("StudentAge")] public int age;
public Class1(){} } 3,实现一个工具类来完成实体类显示到界面上的工作 public class PageUtility { //遍历页面,绑定数据 public void BindData( Control control,object entity) { object temp=null; foreach(Control c in control.Controls) { temp=GetValueFromEntity(c.ClientID,entity);
if(c is TextBox) { ((TextBox)c).Text=temp.ToString(); } if(c.HasControls()) { BindData(c,entity); } } } //获取ControlIDAttribute为controlID的值 private object GetValueFromEntity(string controlID,object entity) { Type t = entity.GetType(); foreach(FieldInfo f in t.GetFields()) { foreach(Attribute attr in Attribute.GetCustomAttributes(f)) { if(attr is ControlIDAttribute && ((ControlIDAttribute)attr)._id == controlID ) { return f.GetValue(entity); } } } return null; } }

|