标记枚举(flags)的使用

本文介绍C#中如何使用标记枚举实现多个标志的组合与判断,包括定义带有Flags特性的枚举类型、在类中声明枚举变量及通过按位或运算符组合标志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    标记枚举是为标记相互包含而使用的,每个成员被赋给一个唯一的按位值。
    用按位或运算符(|)来组合按位标记。用按位和运算符(&)来确定一个标记的存在。
    从组合状态中去掉一个元素用& (~)。
示例代码:

 1None.gifusing System;
 2None.gifusing System.Collections.Generic;
 3None.gifusing System.Text;
 4None.gif
 5None.gifnamespace ConsoleApplication1
 6ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 7InBlock.gif    class Program
 8ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 9InBlock.gif        [Flags]
10InBlock.gif        public enum Contribution
11ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
12InBlock.gif            Pension=0x01,
13InBlock.gif            ProfitSharing=0x02,
14InBlock.gif            CreditBureau=0x04,
15InBlock.gif            SavingsPlan=0x08,
16InBlock.gif            All = Pension | ProfitSharing | CreditBureau | SavingsPlan
17ExpandedSubBlockEnd.gif        }

18InBlock.gif        public class Employee
19ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
20InBlock.gif            private Contribution prop_contributions;
21InBlock.gif            public Contribution contributions
22ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
23ExpandedSubBlockStart.gifContractedSubBlock.gif                get dot.gifreturn prop_contributions; }
24ExpandedSubBlockStart.gifContractedSubBlock.gif                set dot.gif{ prop_contributions = value; }
25ExpandedSubBlockEnd.gif            }

26ExpandedSubBlockEnd.gif        }

27InBlock.gif
28InBlock.gif        public class Starter
29ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
30InBlock.gif            public static void Main()
31ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
32InBlock.gif                Employee bob = new Employee();
33InBlock.gif                bob.contributions = Contribution.ProfitSharing | Contribution.CreditBureau;
34InBlock.gif                if ((bob.contributions & Contribution.ProfitSharing) == Contribution.ProfitSharing)
35ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
36InBlock.gif                    Console.WriteLine("Bob enrolled in profit sharing");
37InBlock.gif                    Console.WriteLine(bob.contributions);
38InBlock.gif                    bob.contributions = bob.contributions & (~Contribution.ProfitSharing);
39InBlock.gif                    Console.WriteLine(bob.contributions);
40ExpandedSubBlockEnd.gif                }

41ExpandedSubBlockEnd.gif            }

42ExpandedSubBlockEnd.gif        }

43ExpandedSubBlockEnd.gif    }

44ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/fang8206/archive/2010/09/18/1830133.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值