C# .NET 获取枚举值的自定义属性
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:49
一、定义一个类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection; namespace XXX.XXX.Utils
{
/// <summary>
/// 备注特性
/// </summary>
public class DescAttribute : Attribute
{
private string m_desc;
public DescAttribute(string desc)
{
this.m_desc = desc;
}
/// <summary>
/// 备注
/// </summary>
public string Desc
{
get { return m_desc; }
set { m_desc = value; }
}
/// <summary>
/// 获取枚举的备注信息
/// </summary>
/// <param name="val">枚举值</param>
/// <returns></returns>
public static string GetEnumDesc(Enum val)
{
Type type = val.GetType();
FieldInfo fd = type.GetField(val.ToString());
if (fd == null)
return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(DescAttribute), false);
string name = string.Empty;
foreach (DescAttribute attr in attrs)
{
name = attr.Desc;
}
return name;
}
}
/// <summary>
/// 枚举扩展类
/// </summary>
public static class EnumExtension
{
/// <summary>
/// 获取枚举的备注信息
/// </summary>
/// <param name="em"></param>
/// <returns></returns>
public static string GetDesc(this Enum em)
{
Type type = em.GetType();
FieldInfo fd = type.GetField(em.ToString());
if (fd == null)
return string.Empty;
object[] attrs = fd.GetCustomAttributes(typeof(DescAttribute), false);
string name = string.Empty;
foreach (DescAttribute attr in attrs)
{
name = attr.Desc;
}
return name;
}
}
}
二、定义一个枚举,并引用如上命名空间
public enum EnumCalculationTag
{
[Desc("This is description")]
A
}
三、获取注解(需引用“一”中的命名空间)
EnumCalculationTag.A.GetDesc()
相关文章
-
c# 【MVC】WebApi通过HttpClient来调用Web Api接口
c# 【MVC】WebApi通过HttpClient来调用Web Api接口
- 互联网
- 2026年04月04日
-
C# conn.open() 外部表不是预期的格式( 读取EXCEL文件出错)
C# conn.open() 外部表不是预期的格式( 读取EXCEL文件出错)
- 互联网
- 2026年04月04日
-
C# DataTable操作,转载
C# DataTable操作,转载
- 互联网
- 2026年04月04日
-
C# .NET 获取枚举值的自定义属性(特性注释备注)信息
C# .NET 获取枚举值的自定义属性(特性注释备注)信息
- 互联网
- 2026年04月04日
-
C# 使用SqlDataAdapter和DataSet来访问数据库
C# 使用SqlDataAdapter和DataSet来访问数据库
- 互联网
- 2026年04月04日
-
C# 不用递归,获取无限层级数据
C# 不用递归,获取无限层级数据
- 互联网
- 2026年04月04日






