C#-枚举

枚举

概念:列举某种数据的所有值
作用:增强代码的可读性,将简单的数据限制在某种范围内可供选择

注意:枚举元素默认为 int ,准许使用枚举的数据类型有:byte、sbyte、short、ushort、uint、long 或者 ulong
特点:每个枚举元素都有固定的枚举值,默认情况下,第一个枚举元素的枚举值为 0 ,接着后面的枚举元素的枚举值依次递增 1

简单示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Text1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 选择多个枚举值:|
            Method(PersonStyle.tall | PersonStyle.rich);
            // 数据类型转换
            // int --> enum
            PersonStyle style1 = (PersonStyle)2;
            // enum --> int
            int num = (int)PersonStyle.handsome;
            // string --> enum
            PersonStyle style2 = (PersonStyle)Enum.Parse(typeof(PersonStyle), "beauty"); 
            // enum --> string
            string str = PersonStyle.white.ToString();
        }
        private static void Method(PersonStyle style)
        {
            // 寻找枚举值所代表的含义
            if ((style & PersonStyle.tall) == PersonStyle.tall)
            {
                Console.WriteLine("高");
            }
            if ((style & PersonStyle.rich) == PersonStyle.rich)
            {
                Console.WriteLine("富");
            }
            if ((style & PersonStyle.white) == PersonStyle.white)
            {
                Console.WriteLine("白");
            }
            if ((style & PersonStyle.handsome) == PersonStyle.handsome)
            {
                Console.WriteLine("帅");
            }
            if ((style & PersonStyle.beauty) == PersonStyle.beauty)
            {
                Console.WriteLine("美");
            }
        }
    }
    [Flags] 
    enum PersonStyle
    {
        tall = 1,
        rich = 2,
        handsome = 4,
        beauty = 8,
        white = 16
    }
}

标志枚举

可以同时选择多个枚举元素
使用标志枚举的前提条件:

(1)任意多个枚举值做 | 运算的结果不能和其他枚举值相同(结果就是:枚举值是 2 的 n 次方)
(2)定义枚举时,使用[Flags]修饰(也就是说看见这个标志,则表示可以选择多个枚举值)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值