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

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
The Last Watchdog
The Last Watchdog
T
Tenable Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
V
Vulnerabilities – Threatpost
F
Fortinet All Blogs
Microsoft Security Blog
Microsoft Security Blog
A
Arctic Wolf
云风的 BLOG
云风的 BLOG
Know Your Adversary
Know Your Adversary
P
Palo Alto Networks Blog
GbyAI
GbyAI
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
MyScale Blog
MyScale Blog
B
Blog
Spread Privacy
Spread Privacy
S
Schneier on Security
Project Zero
Project Zero
L
LINUX DO - 热门话题
M
MIT News - Artificial intelligence
F
Full Disclosure
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
Cyberwarzone
Cyberwarzone
AWS News Blog
AWS News Blog
aimingoo的专栏
aimingoo的专栏
博客园 - 三生石上(FineUI控件)
C
Cybersecurity and Infrastructure Security Agency CISA
Hugging Face - Blog
Hugging Face - Blog
Security Latest
Security Latest
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tailwind CSS Blog
K
Kaspersky official blog
Recent Announcements
Recent Announcements
NISL@THU
NISL@THU
Cisco Talos Blog
Cisco Talos Blog
S
Securelist
P
Privacy & Cybersecurity Law Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
The Exploit Database - CXSecurity.com
V
Visual Studio Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Webroot Blog
Webroot Blog

博客园 - 我有我奥妙

【BenchmarkDotNet】测试多方式的对象映射 【自动注入】.NET8/.NETCore 依赖注入:自动注入项目中所有接口和自定义类 【排名】处理同分数的排名 【Quartz】.Net8使用定时任务 【模型验证】未被异常捕获到 【Ant Design Vue】相关 【根节点】C#找树形数据的根节点Id 【ECharts】图表自定义显示标题 【消息队列】介绍 【Nginx】Windows部署Vue 设计模式(一)-介绍 【.NetCore】创建本机的静态文件服务器 NLog(一)-使用示例 【nssm】windows上netcore注册为服务 【字符串排序】C#和前端js排序问题 【长路经】C#读取文件抛出FileNotFoundException异常 【RestSharp】常用的几个请求方式 【笔记软件】Obsidian的使用 【浏览器扩展】编写Firefox和Chrome的扩展程序
【C#】枚举值
我有我奥妙 · 2025-04-13 · via 博客园 - 我有我奥妙

示例代码

    public enum TypeEnum
    {
        [Text("进行中")]
        Doing = 1,
        [Text("完成")]
        Done = 2,
        [Text("已被删除")]
        Deleted = 9,
    }
    public class TextAttribute : Attribute
    {
        public TextAttribute(string value)
        {
            Value = value;
        }
        public string Value { get; set; }
    }

    public static class Utils
    {
        public static T ToEnum<T>(this int value) where T : struct, Enum
        {
            if (Enum.TryParse(value.ToString(), out T e) == false || Enum.IsDefined(typeof(T), e) == false)
                throw new Exception(value + " 转换失败");

            return e;
        }

        public static T ToEnum<T>(this string value) where T : struct, Enum
        {
            if (Enum.TryParse(value, out T e) == false || Enum.IsDefined(typeof(T), e) == false)
                throw new Exception(value + " 转换失败");

            return e;
        }
    }

测试代码

        static void Test06()
        {
            TypeEnum typeEnum = TypeEnum.Doing;
            int v1 = (int)typeEnum;
            string v2 = typeEnum.ToString();
            string v3 = string.Empty;

            var enumType = typeEnum.GetType();
            {
                var fieldInfo = enumType.GetField(typeEnum.ToString());
                var attrs = fieldInfo.GetCustomAttributes(typeof(TextAttribute), false);
                if (attrs.Length == 1)
                {
                    v3 = ((TextAttribute)attrs[0]).Value;
                }
            }

            Console.WriteLine("int=>" + v1);//1
            Console.WriteLine("name=>" + v2);//Doing
            Console.WriteLine("text=>" + v3);//进行中
            Console.WriteLine("");

            int n1 = 1;//转换成功
            int n2 = 5;//转换失败
            string s1 = "Doing";//转换成功
            string s2 = "DDDD";//转换失败

            List<object> lst = new List<object> { n1, n2, s1, s2, };
            foreach (var item in lst)
            {
                try
                {
                    var e = item.ToString().ToEnum<TypeEnum>();

                    Console.WriteLine($"{item} => 转换成功");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{item} => 转换失败,{ex.Message}");
                }
            }
            Console.WriteLine("");

            foreach (TypeEnum value in Enum.GetValues(enumType))
            {
                string name = Enum.GetName(enumType, value);
                var fieldInfo = enumType.GetField(name);
                var attrs = fieldInfo.GetCustomAttributes(typeof(TextAttribute), false);
                if (attrs.Length == 1)
                {
/*
Value: 1, Name: Doing, Text: 进行中
Value: 2, Name: Done, Text: 完成
Value: 9, Name: Deleted, Text: 已被删除
*/
                    Console.WriteLine($"Value: {(int)value}, Name: {name}, Text: {((TextAttribute)attrs[0]).Value}");
                }
            }
        }

结果

int=>1
name=>Doing
text=>进行中

1 => 转换成功
5 => 转换失败,5 转换失败
Doing => 转换成功
DDDD => 转换失败,DDDD 转换失败

Value: 1, Name: Doing, Text: 进行中
Value: 2, Name: Done, Text: 完成
Value: 9, Name: Deleted, Text: 已被删除
ok