• 在C#中如何读取枚举值的描述属性


    在C#中,有时候我们需要读取枚举值的描述属性,也就是说这个枚举值代表了什么意思。比如本文中枚举值 Chinese ,我们希望知道它代表意思的说明(即“中文”)。

    有下面的枚举:

    1
    2
    3
    4
    5
    6
    public enum EnumLanugage
    {
        [System.ComponentModel.Description("中文")]
        Chinese,
        English
    }

    我们要获取的就是 Chinese 中的说明文字“中文”。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public string GetEnumDescription(Enum enumValue)
    {
        string str = enumValue.ToString();
        System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
        object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
        if (objs == null || objs.Length == 0) return str;
        System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
        return da.Description;
    }

    调用 GetEnumDescription(EnumLanguage.Chinese) 后 将返回“中文”,如果换成 EnumLanguage.English ,由于在 English 上没有定义 Description ,将直接返回枚举名称 English 。

  • 相关阅读:
    k8s-学习笔记12-权限体系
    Linux上磁盘热插拔
    delphi hashmap
    my gcc project
    gcc dll 导出问题 GTK+Glade3 Gtk-WARNING **: Could not find signal handler 问题最终解析
    c/c++字符串定义及使用的对比
    gcc printf()打印char* str
    gcc选项-g与-rdynamic的异同
    GCC编译,库的编译使用及Makefile
    gcc test
  • 原文地址:https://www.cnblogs.com/xiaofengfeng/p/4125003.html
Copyright © 2020-2023  润新知