雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

c#获取枚举的Description

2024-10-10 19

要获取 C# 中枚举的描述(Description),可以使用反射和自定义属性来实现。

首先,需要在枚举值上定义自定义属性(Custom Attribute),用于存储描述信息。例如:

public enum MyEnum
{
    [Description("This is the first value")]
    Value1,

    [Description("This is the second value")]
    Value2,

    [Description("This is the third value")]
    Value3
}

接下来,可以编写一个扩展方法来获取枚举值的描述。例如:

using System;
using System.ComponentModel;
using System.Reflection;

public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        FieldInfo field = value.GetType().GetField(value.ToString());

        DescriptionAttribute attribute
                = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                    as DescriptionAttribute;

        return attribute == null ? value.ToString() : attribute.Description;
    }
}

现在,可以使用该扩展方法获取枚举值的描述。例如:

MyEnum myValue = MyEnum.Value1;
string description = myValue.GetDescription();
Console.WriteLine(description); // 输出:This is the first value

注意,上述方法中使用了 System.ComponentModel 命名空间中的 DescriptionAttribute 类来定义自定义属性。如果在项目中没有使用该命名空间,则需要添加对 System.ComponentModel 命名空间的引用。

更新于:8天前
赞一波!

文章评论

评论问答