using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CloudBuilder.Core.Extensions
{
using System;
using System.Collections.Concurrent;
using System.Reflection;
public static class CustomAttributeExtensions
{
///
/// Cache Data
///
private static readonly ConcurrentDictionary Cache = new ConcurrentDictionary();
///
/// 获取CustomAttribute Value
///
/// Attribute的子类型
/// TReturn的子类型
/// 头部标有CustomAttribute类的类型
/// 取Attribute具体哪个属性值的匿名函数
/// 返回Attribute的值,没有则返回null
public static TReturn GetCustomAttributeValue(this Type sourceType, Func attributeValueAction)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, null);
}
///
/// 获取CustomAttribute Value
///
/// Attribute的子类型
/// TReturn的子类型
/// 头部标有CustomAttribute类的类型
/// 取Attribute具体哪个属性值的匿名函数
/// field name或property name
/// 返回Attribute的值,没有则返回null
public static TReturn GetCustomAttributeValue(this Type sourceType, Func attributeValueAction, string propertyName)
where TAttribute : Attribute
{
return _getAttributeValue(sourceType, attributeValueAction, propertyName);
}
#region private methods
private static TReturn _getAttributeValue(Type sourceType, Func attributeFunc, string propertyName)
where TAttribute : Attribute
{
var cacheKey = BuildKey(sourceType, propertyName);
var value = Cache.GetOrAdd(cacheKey, k => GetValue(sourceType, attributeFunc, propertyName));
if (value is TReturn) return (TReturn)Cache[cacheKey];
return default(TReturn);
}
private static string BuildKey(Type type, string propertyName) where TAttribute : Attribute
{
var attributeName = typeof(TAttribute).FullName;
if (string.IsNullOrEmpty(propertyName))
{
return type.FullName + "." + attributeName;
}
return type.FullName + "." + propertyName + "." + attributeName;
}
private static TReturn GetValue(this Type type, Func attributeValueAction, string name)
where TAttribute : Attribute
{
TAttribute attribute = default(TAttribute);
if (string.IsNullOrEmpty(name))
{
attribute = type.GetCustomAttribute(false);
}
else
{
var propertyInfo = type.GetProperty(name);
if (propertyInfo != null)
{
attribute = propertyInfo.GetCustomAttribute(false);
}
else
{
var fieldInfo = type.GetField(name);
if (fieldInfo != null)
{
attribute = fieldInfo.GetCustomAttribute(false);
}
else
{
var methodInfo = type.GetMethod(name);
if (methodInfo != null)
{
attribute = methodInfo.GetCustomAttribute(false);
}
}
}
}
return attribute == null ? default(TReturn) : attributeValueAction(attribute);
}
#endregion
}
}