//############################################################ // https://github.com/yuzhengyang // author:yuzhengyang //############################################################ using System; using System.Collections.Generic; using System.Linq; namespace Azylee.Core.ReflectionUtils.AttributeUtils { public static class CustomAttributeHelper { /// /// Cache Data /// private static readonly Dictionary Cache = new Dictionary(); /// /// 获取CustomAttribute Value /// /// Attribute的子类型 /// 头部标有CustomAttribute类的类型 /// 取Attribute具体哪个属性值的匿名函数 /// 返回Attribute的值,没有则返回null public static string GetCustomAttributeValue(this Type sourceType, Func attributeValueAction) where T : Attribute { return GetAttributeValue(sourceType, attributeValueAction, null); } /// /// 获取CustomAttribute Value /// /// Attribute的子类型 /// 头部标有CustomAttribute类的类型 /// 取Attribute具体哪个属性值的匿名函数 /// field name或property name /// 返回Attribute的值,没有则返回null public static string GetCustomAttributeValue(this Type sourceType, Func attributeValueAction, string name) where T : Attribute { return GetAttributeValue(sourceType, attributeValueAction, name); } private static string GetAttributeValue(Type sourceType, Func attributeValueAction, string name) where T : Attribute { var key = BuildKey(sourceType, name); if (!Cache.ContainsKey(key)) { CacheAttributeValue(sourceType, attributeValueAction, name); } return Cache[key]; } /// /// 缓存Attribute Value /// private static void CacheAttributeValue(Type type, Func attributeValueAction, string name) { var key = BuildKey(type, name); var value = GetValue(type, attributeValueAction, name); lock (key + "_attributeValueLockKey") { if (!Cache.ContainsKey(key)) { Cache[key] = value; } } } private static string GetValue(Type type, Func attributeValueAction, string name) { object attribute = null; if (string.IsNullOrEmpty(name)) { attribute = type.GetCustomAttributes(typeof(T), false).FirstOrDefault(); } else { var propertyInfo = type.GetProperty(name); if (propertyInfo != null) { attribute = propertyInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault(); } var fieldInfo = type.GetField(name); if (fieldInfo != null) { attribute = fieldInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault(); } } return attribute == null ? null : attributeValueAction((T)attribute); } /// /// 缓存Collection Name Key /// private static string BuildKey(Type type, string name) { if (string.IsNullOrEmpty(name)) { return type.FullName; } return type.FullName + "." + name; } } }