using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyCode.Project.Infrastructure.JackYun
{
///
/// 枚举属性。
///
[AttributeUsage(AttributeTargets.Field)]
public class EnumAttribute : Attribute
{
#region 构造器
///
/// 构造器。
///
/// 枚举名
/// 枚举值
public EnumAttribute(string text, string value) : this(text, value, null) { }
///
/// 构造器。
///
/// 枚举名
/// 枚举值
/// 颜色值
public EnumAttribute(string text, string value, string colorText)
{
this.Text = text;
this.Value = value;
this.ColorText = colorText;
}
#endregion
#region 变量
///
/// 并发控制锁对象。
///
private static readonly object __LOCK__ = new object();
///
/// 属性缓存对象。
///
private static Dictionary> cachedObj = new Dictionary>();
#endregion
#region 属性
///
/// 获取或设置 枚举名。
///
public string Text { get; set; }
///
/// 获取或设置 枚举值。
///
public string Value { get; set; }
///
/// 获取或设置 颜色值。
///
public string ColorText { get; set; }
#endregion
#region 获取指定对象的枚举属性
///
/// 获取指定对象的枚举属性。
///
/// 源对象
///
public static EnumAttribute GetAttribute(object obj)
{
//设置对象缓存键。
var cacheKey1 = obj.GetType().FullName;
//从缓存中获取。
if (cachedObj.ContainsKey(cacheKey1))
return cachedObj[cacheKey1].ContainsKey(obj.ToString()) ? cachedObj[cacheKey1][obj.ToString()] : null;
//动态反射获取。
lock (__LOCK__)
{
var dic = new Dictionary();
foreach (var fi in obj.GetType().GetFields())
{
object[] eds = fi.GetCustomAttributes(typeof(EnumAttribute), false);
if (eds.Length == 1)
{
if (!dic.ContainsKey(fi.Name))
dic.Add(fi.Name, (EnumAttribute)eds[0]);
}
}
if (!cachedObj.ContainsKey(cacheKey1))
cachedObj.Add(cacheKey1, dic);
return dic.ContainsKey(obj.ToString()) ? dic[obj.ToString()] : null;
}
}
#endregion
}
}