惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
S
SegmentFault 最新的问题
Engineering at Meta
Engineering at Meta
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google DeepMind News
Google DeepMind News
博客园_首页
云风的 BLOG
云风的 BLOG
月光博客
月光博客
I
InfoQ
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
美团技术团队
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
D
Docker
F
Fortinet All Blogs
N
Netflix TechBlog - Medium
博客园 - 叶小钗
Martin Fowler
Martin Fowler
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog

博客园 - 木乃伊人

MCP Server部署到云端服务器 MCP 开发 VS Code 搭建LangChain开发环境 VSCode Unable to import XXX 问题解决记录 大模型应用开发-聊天机器人-保存聊天记录 try-catch中的throw和throw ex的区别 TDD Google Chrome 默认非安全端口列表 EF Core的预先加载、延迟加载、实体追踪 同步、异步、回调 软件设计原则 UML类图 Seq Serilog 多线程整理 Vuex和Pinia Vue3+TS+Vite+pinia Vite创建Vue3项目 闭包 IdentitySrever4 ElasticSearch 前端防止重复提交案例
枚举
木乃伊人 · 2024-04-03 · via 博客园 - 木乃伊人
// 枚举
public enum enumStudent
{
    [Description("性别")]
    sex = 0,
    [Description("年龄")]
    age = 1,
}
 
// 获取方法
public string GetDescriptionByEnum(Enum enumValue)
{
    string value = enumValue.ToString();
    System.Reflection.FieldInfo field = enumValue.GetType().GetField(value);
    object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
    if (objs.Length == 0)    //当描述属性没有时,直接返回名称
        return value;
    DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
    return descriptionAttribute.Description;
}
 
 
// 调用示例
GetDescriptionByEnum(enumStudent.age) → 年龄
 
 
public T GetEnumByDescription<T>(string description) where T : Enum
{
    System.Reflection.FieldInfo[] fields = typeof(T).GetFields();
    foreach(System.Reflection.FieldInfo field in fields)
    {
        object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);    //获取描述属性
        if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description)
        {
            return (T)field.GetValue(null);
        }
    }
 
    throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
}
 
// 调用示例