一、通过DataPropertyAttribute特性过滤实体的数据属性
DataBinder在进行数据绑定的时候,并没有对作为数据源的对象作任何限制,也就是说任何类型的对象均可作为数据绑定的数据源。控件这里指TextBox、Label等这样绑定标量数值的控件)绑定值来源于数据源实体的某个属性。但是一个类型的属性可能有很多,我们需要某种筛选机制将我们需要的“数据属性”提取出来。这里我们是通过在属性上应用DataPropertyAttribute一个特性来实现的。
简单起见,我不曾为DataPropertyAttribute定义任何属性成员。DataPropertyAttribute中定义了一个静态的GetDataProperties方法,得到给定实体类型的所有数据属性的名称。但是为了避免频繁地对相同实体类型进行反射,该方法对得到的属性名称数组进行了缓存。
- [AttributeUsage( AttributeTargets.Property, AllowMultiple = false,Inherited = true)]
- public class DataPropertyAttribute: Attribute
- {
- private static Dictionary<Type, string[]> dataProperties = new Dictionary<Type, string[]>();
- public static string[] GetDataProperties(Type entityType)
- {
- Guard.ArgumentNotNullOrEmpty(entityType, "entityType");
- if (dataProperties.ContainsKey(entityType))
- {
- return dataProperties[entityType];
- }
- lock (typeof(DataPropertyAttribute))
- {
- if (dataProperties.ContainsKey(entityType))
- {
- return dataProperties[entityType];
- }
- var properties = (from property in entityType.GetProperties()
- where property.GetCustomAttributes(typeof(DataPropertyAttribute), true).Any()
- select property.Name).ToArray();
- dataProperties[entityType] = properties;
- return properties;
- }
- }
- }
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。