• 枚举的总结


    直接上代码:

    namespace EnumStudy
    {
        public enum Days:byte//枚举继承什么类型就是什么类型
        {
            [Description("星期1")]
            Monday=1,
            [Description("星期2")]
            Tuesday,
            [Description("星期3")]
            Wednesday,
            [Description("星期4")]
            Thursday,
            [Description("星期5")]
            Friday,
            [Description("星期6")]
            Saturday,
            [Description("星期7")]
            Sunday,
        }
    
    
    }

    使用:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace EnumStudy
    {
        public class UseerEnum
        {
            public void Run()
            {
                //枚举转字符串
                string foo = Days.Saturday.ToString();//"Saturday"
                string foo1 = Enum.GetName(typeof(Days),6);//"Saturday"
    
                //字符串转枚举
                Enum.TryParse("Saturday",out Days bar);//true,bar=Days.Saturday
                Days day = (Days)Enum.Parse(typeof(Days), "Saturday");// Days.Saturday
    
                //枚举转数字
                byte foo2 = (byte)Days.Friday;//5
    
                //数字转枚举
                Days foo3=(Days)2;//Days.Tuesday
    
                //获取枚举所属类型
                Type foo4 = Enum.GetUnderlyingType(typeof(Days));
    
                //获取所有枚举成员
                Array foo5 = Enum.GetValues(typeof(Days));
    
                //获取所有枚举成员的字段名
                string[] foo6 = Enum.GetNames(typeof(Days));
    
    
                //默认值
                Days d = (Days)21;//不会报错
                Enum.IsDefined(typeof(Days), d);//false
    
                //枚举默认值永远为0
                var z = default(Days);
    
                //获取枚举描述
                string des = GetDescription(Days.Friday);
    
            }
    
            public  string GetDescription(Enum val)
            {
                var field = val.GetType().GetField(val.ToString());
                var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
                if (customAttribute == null) { return val.ToString(); }
                else { return ((DescriptionAttribute)customAttribute).Description; }
            }
        }
    }
  • 相关阅读:
    解决WPF中异常导致的程序Crash
    Python---pep8规范
    Python---13面向对象编程
    Python---12函数式编程------12.3匿名函数&装饰器&偏函数
    Python---12函数式编程------12.2返回函数
    Python中*args和**kwargs的区别
    测试干货-接口测试(接口测试工具+接口测试用例)
    Python---13靠谱的Pycharm安装详细教程
    Python---12函数式编程------12.1高阶函数
    Python---11模块
  • 原文地址:https://www.cnblogs.com/zhuyapeng/p/12908899.html
Copyright © 2020-2023  润新知