c# - 如何从枚举成员获取 DescriptionAttribute 值

标签 c# attributes

我有一个枚举类型

public enum DataType:int
    {   
        None = 0,
        [Description("A")]
        Alpha = 1,
        [Description("N")]
        Numeric,
        [Description("AN")]
        AlphaNumeric,
        [Description("D")]
        Date
    }

如何检索例如 Alpha 的描述属性值。

例如(理想):DataType.Alpha.Attribute 应该给 "A"

最佳答案

使用这个

private string GetEnumDescription(Enum value)
{
    // Get the Description attribute value for the enum value
    FieldInfo fi = value.GetType().GetField(value.ToString());
    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attributes.Length > 0)
        return attributes[0].Description;
    else
        return value.ToString();
}

关于c# - 如何从枚举成员获取 DescriptionAttribute 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959380/

相关文章:

c# - 为什么 MenuItems 不能与 DynamicResource 一起使用?

c# - 来自 KeyVaultKeyResolver 的 Azure rsaKey 始终为 null

c# - 使用 C# 读取文件的创建最后修改时间戳

c# - 属性或注释的酷用途(CLR 或 Java)?

javascript - 获取元素属性

c# - Selenium : Firefox Driver, 在 c# 中使用 SelectElement 从下拉列表中选择一个项目无法正常工作

c# - 如果在 ASP.NET MVC 区域名称中强制使用 "public"和 "private"等关键字,我会面临什么问题?

c# - 在 C# 中序列化没有 GMT 的日期时间

Python静态方法,为什么?

angularjs - 如何以 Angular 手动获取$attr