如何使用枚举的组合值

有时我们需要将枚举定义为1,2,4,8.......的值,这样当传入一个3,那么就是表示1,2的组合,如果传入7,那就表示1,2,4的组合。要实现这种功能我们需要用到FlagsAttribute。具体用法如下:
1.定义Enum。
[Flags]
public enum FormType
{
    Reimburse
=1,
    Payment
=2,
    Precharge
=4,
    PO
=8
}
2.组合枚举值的判断:
public static void Print(FormType ft)
    
{
        
if((ft&FormType.Reimburse)==FormType.Reimburse)//与判断
        {
            Console.WriteLine(
"Reimburse");
        }

        
if((ft&FormType.Payment)==FormType.Payment)
        
{
            Console.WriteLine(
"Payment");
        }

        
if((ft&FormType.Precharge)==FormType.Precharge)
        
{
            Console.WriteLine(
"Precharge");
        }

        
if((ft&FormType.PO)==FormType.PO)
        
{
            Console.WriteLine(
"PO");
        }

        Console.WriteLine(
"End");
    }

3.生成组合枚举:
FormType ft=FormType.Reimburse|FormType.PO;
Print(ft);
运行输出的结果就是:
Reimburse
PO
【本文章出自博客园深蓝居,转载请注明作者出处,如果您觉得博主的文章对您有很大帮助,欢迎支付宝(studyzy@163.com)对博主进行打赏。】
原文地址:https://www.cnblogs.com/studyzy/p/924548.html