ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Enum.GetDescription

获取项目中分配给 Enum 的描述属性。

Source

public static class EnumExtensions
{
    public static string GetDescription(this Enum @enum)
    {
        var fi = @enum.GetType().GetField(@enum.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes != null && attributes.Length > 0)
            return attributes[0].Description;
        else
            return @enum.ToString();
    }

    public static string GetDescription<TEnum>(this object @object) where TEnum : struct
    {
        return Enum.TryParse(@object.ToString(), out TEnum @enum) ? (@enum as Enum).GetDescription() : @object.ToString();
    }
}

Example

public enum ApiStatus
{
    [Description("成功")]
    OK = 0,
    [Description("资源未找到")]
    NotFound = 2,
    [Description("拒绝访问")]
    AccessDenied = 3
}
static void Main(string[] args)
{
    Console.WriteLine(ApiStatus.Ok.GetDescription()); // "成功"
    Console.WriteLine(0.GetDescription<ApiStatus>()); // "成功"
}

Author: 向以胜

Submitted on: 29 jun. 2021

Language: csharp

Type: System.Enum

Views: 7252