• C#枚举


    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;
    
    namespace ConsoleApp4
    {
    
        static class Program
        {
            public static DB EnumObj { get; set; }
            static void Main(string[] args)
            {
                var aaa = EnumObj.Split();
                var bbb = (DB)7;
                var ccc = (DB)15;
    
                //遍历枚举
                foreach (DB enum2 in Enum.GetValues(typeof(DB)))
                {
                    //enum2 = DB.Read;
                    var Int = (int)enum2;
                    var Str = enum2.ToString();
                    var Description = GetDescriptionByEnum(enum2);
                }
                Console.ReadKey();
            }
    
            // Flags 可以让枚举值以枚举值之和形式提现。有一个前提:(int)大的枚举值必须大过其小于此值枚举值之和
            //比如:ReadWrite > None + Write + Read
            [Flags]
            public enum DB
            {
                None = 0,
                Write = 1,
                [Description("")]
                Read = 2,
                ReadWrite = 4,
                Max = 8
            }
            //枚举、字符串、数字相互转换
            public static int EnumConvertToInt(DB db) => (int)db;
            public static string EnumConvertToString(DB db) => db.ToString();
            public static DB StringConvertToEnum(string str) => (DB)Enum.Parse(typeof(DB), str);
            public static DB IntConvertToEnum(int i) => (DB)i;
            // 将枚举转化为IEnumerable列表
            public static IEnumerable<T> Split<T>(this T enums) => Enum.GetValues(enums.GetType()).Cast<T>();
    
            /// <summary>
            /// 获取枚举的 Description 值
            /// </summary>
            /// <param name="enumValue"></param>
            /// <returns></returns>
            public static string GetDescriptionByEnum(Enum enumValue)
            {
                string value = enumValue.ToString();
                FieldInfo field = enumValue.GetType().GetField(value);
                //获取描述属性  
                object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                //当描述属性没有时,直接返回名称
                return objs.Length == 0 ? value : ((DescriptionAttribute)objs[0]).Description;
            }
        }
    }
  • 相关阅读:
    angular运行报错“Cannot find module 'ng2-translate'.”
    切换分支
    下载angular项目报错[ERROR] ionic-app-scripts has unexpectedly closed (exit code 1).
    通过原生SQL判断数据是否存在
    多图合并一张长图脚本
    科大讯飞--新冠肺炎检测赛道第八分享
    Mysql定时任务
    Mysql导出数据结构 or 数据
    G6Editor 边的参数配置
    百度坐标转腾讯坐标
  • 原文地址:https://www.cnblogs.com/RainFate/p/12093815.html
Copyright © 2020-2023  润新知