Files
YunTongJackYunTask/Reportapi/MyCode.Project.Infrastructure/JackYun/EnumAttribute.cs
2025-07-07 09:35:11 +08:00

111 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyCode.Project.Infrastructure.JackYun
{
/// <summary>
/// 枚举属性。
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class EnumAttribute : Attribute
{
#region
/// <summary>
/// 构造器。
/// </summary>
/// <param name="text">枚举名</param>
/// <param name="value">枚举值</param>
public EnumAttribute(string text, string value) : this(text, value, null) { }
/// <summary>
/// 构造器。
/// </summary>
/// <param name="text">枚举名</param>
/// <param name="value">枚举值</param>
/// <param name="colorText">颜色值</param>
public EnumAttribute(string text, string value, string colorText)
{
this.Text = text;
this.Value = value;
this.ColorText = colorText;
}
#endregion
#region
/// <summary>
/// 并发控制锁对象。
/// </summary>
private static readonly object __LOCK__ = new object();
/// <summary>
/// 属性缓存对象。
/// </summary>
private static Dictionary<string, Dictionary<string, EnumAttribute>> cachedObj = new Dictionary<string, Dictionary<string, EnumAttribute>>();
#endregion
#region
/// <summary>
/// 获取或设置 枚举名。
/// </summary>
public string Text { get; set; }
/// <summary>
/// 获取或设置 枚举值。
/// </summary>
public string Value { get; set; }
/// <summary>
/// 获取或设置 颜色值。
/// </summary>
public string ColorText { get; set; }
#endregion
#region
/// <summary>
/// 获取指定对象的枚举属性。
/// </summary>
/// <param name="obj">源对象</param>
/// <returns></returns>
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<string, EnumAttribute>();
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
}
}