/// <summary> /// 从类型所有的装饰特性中,获取某类型的第一个匹配特性 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="typeDecoratorInfo"></param> /// <param name="decoratorAttrType"></param> /// <returns></returns> public static T GetDecorateAttr <T>(this TypeDecoratorInfo typeDecoratorInfo) where T : BaseDecorateAttribute { var attr = typeDecoratorInfo.TypeDecoratorAttrs.SingleOrDefault(a => a.GetType() == typeof(T)); return(attr == null ? null : (T)attr); }
/// <summary> /// 从类型所有的装饰特性中,获取某类型的所有匹配特性 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="typeDecoratorInfo"></param> /// <param name="decoratorAttrType"></param> /// <returns></returns> public static List <T> GetDecorateAttrs <T>(this TypeDecoratorInfo typeDecoratorInfo) where T : BaseDecorateAttribute { var attrs = typeDecoratorInfo.TypeDecoratorAttrs.Where(a => a.GetType() == typeof(T)); return(attrs == null ? null : attrs.Cast <T>().ToList()); }
public static TypeDecoratorInfo CreateInstance(Type exportType) { if (exportType == null) { throw new ArgumentNullException("importDTOType"); } var key = exportType; if (Table[key] != null) { return((TypeDecoratorInfo)Table[key]); } TypeDecoratorInfo typeDecoratorInfo = new TypeDecoratorInfo() { TypeDecoratorAttrs = new List <BaseDecorateAttribute>() { }, PropertyDecoratorInfos = new List <PropertyDecoratorInfo>() { } }; //全局装饰特性 typeDecoratorInfo.TypeDecoratorAttrs.AddRange(exportType.GetCustomAttributes <BaseDecorateAttribute>()); //列装饰特性 List <PropertyInfo> props = exportType.GetProperties().ToList().Where(p => p.IsDefined(typeof(ColNameAttribute))).ToList(); for (int i = 0; i < props.Count(); i++) { typeDecoratorInfo.PropertyDecoratorInfos.Add( new PropertyDecoratorInfo { ColIndex = i, DecoratorAttrs = props[i].GetCustomAttributes <BaseDecorateAttribute>()?.ToList() }); } Table[key] = typeDecoratorInfo; return(typeDecoratorInfo); }
/// <summary> /// 获取所有的装饰器 /// </summary> /// <returns></returns> private static List <IDecorator> GetDecorators <T>() where T : class, new() { List <IDecorator> decorators = new List <IDecorator>(); List <BaseDecorateAttribute> attrs = new List <BaseDecorateAttribute>(); TypeDecoratorInfo typeDecoratorInfo = TypeDecoratorInfoFactory.CreateInstance(typeof(T)); attrs.AddRange(typeDecoratorInfo.TypeDecoratorAttrs); typeDecoratorInfo.PropertyDecoratorInfos.ForEach(a => attrs.AddRange(a.DecoratorAttrs)); attrs.Distinct(new DecoratorAttributeComparer()).ToList().ForEach (a => { var decorator = DecoratorFactory.CreateInstance(a.GetType()); if (decorator != null) { decorators.Add(decorator); } }); return(decorators); }