欢迎投稿

今日深度:

一句代码实现批量数据绑定 下(1)(2)

一、通过DataPropertyAttribute特性过滤实体的数据属性

DataBinder在进行数据绑定的时候,并没有对作为数据源的对象作任何限制,也就是说任何类型的对象均可作为数据绑定的数据源。控件这里指TextBox、Label等这样绑定标量数值的控件)绑定值来源于数据源实体的某个属性。但是一个类型的属性可能有很多,我们需要某种筛选机制将我们需要的“数据属性”提取出来。这里我们是通过在属性上应用DataPropertyAttribute一个特性来实现的。

简单起见,我不曾为DataPropertyAttribute定义任何属性成员。DataPropertyAttribute中定义了一个静态的GetDataProperties方法,得到给定实体类型的所有数据属性的名称。但是为了避免频繁地对相同实体类型进行反射,该方法对得到的属性名称数组进行了缓存。

  1. [AttributeUsage( AttributeTargets.Property, AllowMultiple = false,Inherited = true)]  
  2.  public class DataPropertyAttribute: Attribute  
  3.  {  
  4.      private static Dictionary<Type, string[]> dataProperties = new Dictionary<Type, string[]>();  
  5.      public static string[] GetDataProperties(Type entityType)  
  6.      {  
  7.          Guard.ArgumentNotNullOrEmpty(entityType, "entityType");  
  8.          if (dataProperties.ContainsKey(entityType))  
  9.          {  
  10.              return dataProperties[entityType];  
  11.          }  
  12.          lock (typeof(DataPropertyAttribute))  
  13.          {  
  14.              if (dataProperties.ContainsKey(entityType))  
  15.              {  
  16.                  return dataProperties[entityType];  
  17.              }  
  18.              var properties = (from property in entityType.GetProperties()  
  19.                                where property.GetCustomAttributes(typeof(DataPropertyAttribute), true).Any()  
  20.                                select property.Name).ToArray();  
  21.              dataProperties[entityType] = properties;  
  22.              return properties;  
  23.          }  
  24.      }  
  25.  }  

 


www.htsjk.Com true http://www.htsjk.com/shujukujc/18883.html NewsArticle 一、通过DataPropertyAttribute特性过滤实体的数据属性 DataBinder在进行数据绑定的时候,并没有对作为数据源的对象作任何限制,也就是说任何类型的对象均可...
评论暂时关闭