返回

c#获取枚举的Description

2023-04-14 c# c#获取枚举 枚举的Description 枚举 Description 2535 0

要获取 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 命名空间的引用。

您可能感兴趣:

阿里云 云服务器 99元1年 2核2G 3M固定带宽 续费与新购同价

DOVE 网络加速器 梯子 免费 试用

顶部