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 = "左";
posted @ 2019-11-05 14:55  懵咚  阅读(1136)  评论(0编辑  收藏  举报