/// <summary>
/// 注解的扩展
/// </summary>
public static class AttributeExtensions
{
/// <summary>
/// 返回枚举值的描述信息。
/// </summary>
/// <param name="value">要获取描述信息的枚举值。</param>
/// <returns>枚举值的描述信息。</returns>
public static string GetEnumDesc<T>(int value)
{
Type enumType = typeof(T);
DescriptionAttribute attr = null;
// 获取枚举常数名称。
string name = Enum.GetName(enumType, value);
if (name != null)
{
// 获取枚举字段。
FieldInfo fieldInfo = enumType.GetField(name);
if (fieldInfo != null)
{
// 获取描述的属性。
attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute;
}
}
// 返回结果
if (attr != null && !string.IsNullOrEmpty(attr.Description))
return attr.Description;
else
return string.Empty;
}
/// <summary>
/// 返回枚举项的描述信息。
/// </summary>
/// <param name="e">要获取描述信息的枚举项。</param>
/// <returns>枚举项的描述信息。</returns>
【笔记】C# Attribute 扩展工具类
最新推荐文章于 2022-03-03 16:54:49 发布
本文介绍了C#中Attribute的概念,探讨了其在代码注解和元数据中的作用,并分享了一个实用的Attribute扩展工具类,包含如何自定义Attribute以及在运行时检索和使用这些Attribute的示例。
摘要由CSDN通过智能技术生成