编程语言
首页 > 编程语言> > C#获取枚举描述文本

C#获取枚举描述文本

作者:互联网

定义一个表示方向的枚举:

public enum Position
{
    [Description("上")]
    Up,
    [Description("下")]
    Down,
    [Description("左")]
    Left,
    [Description("右")]
    Right
}

获取枚举的描述:

public static string GetDescription<TEnum>(TEnum @enum)
{
    FieldInfo fieldInfo = @enum.GetType().GetField(@enum.ToString());
    DescriptionAttribute[] descriptionAttributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
    return descriptionAttributes.Length > 0 ? descriptionAttributes[0].Description : @enum.ToString();
}

使用示例:

Position position = Position.Left;
var description = GetDescription(position); // description = "左";

标签:Description,DescriptionAttribute,C#,enum,descriptionAttributes,枚举,Position,文本
来源: https://www.cnblogs.com/gme5/p/11798445.html