简体   繁体   中英

How to make [Flags] enum and switch case work together?

How to make [Flags] enum and switch case work together? Very desirable to make it looks simple. Similar Questions asked many times, but never directly to [Flags] enum.

If M1 set execute operation 1,

if M2 set execute operation2 ,

if BOTH M1 and M2 then set execute operation 1 and 2.

 [Flags]
    public enum TST
    {
        M1 =1,
        M2 =2,
        M3 =4
    }

 public void PseudoCode()
    {

        TST t1 = TST.M1 | TST.M3; //1+2= 3

        switch( t1)
        {
            case TST.M1:
                {
                    //Do work if Bit 1 set
                }
            case TST.M2:
                {
                    //Do work if Bit 2 set
                }
            case TST.M3:
                {
                    //Do work if Bit 3 set
                }
            default:
                {
                    //nothing set;
                    break;
                }
        }

    }

I also quite sure a lot of people want to know how to make it work. Request fix of C#?

This will execute for any bit set

for example

ExecuteOnFlagValue(TST.M1 | TST.M3); //1+2= 3

Will execute code for bits 1 and 3

public void ExecuteOnFlagValue(TST value) {
    if (value & TST.M1 == TST.M1) {
        //Do work if bit 1
    }
    if (value & TST.M2 == TST.M2) {
        //Do work if bit 2
    }
    if (value & TST.M3 == TST.M3) {
        //Do work if bit 3
    }
}

You can't do that with switch in c#, since once a case is executed, no other case will be executed.
You can think of a switch statement as a shorter way to write if... else if... else... constructs - where each case is an if , and the default is the final else :

This means that the following switch statement:

switch( t1)
{
    case TST.M1:
        //Do work if Bit 1 set
        break;
    case TST.M2:
        //Do work if Bit 2 set
        break;
    case TST.M3:
        //Do work if Bit 3 set
        break;
    default:
        //nothing set;
        break;
}

Is equivalent to the following if...else if... else construct:

if(t1 == TST.M1)
{
    //Do work if only Bit 1 set
}
else if (t1 == TST.M2)
{
    //Do work if only Bit 2 set
}
else if (t1 == TST.M3)
{
    //Do work if only Bit 3 set
}
else
{
    //nothing set or multiple bits set
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM