Switch on Enum (with Flags attribute) without declaring every possible combination?

后端 未结 9 2037
忘掉有多难
忘掉有多难 2021-01-31 14:15

how do i switch on an enum which have the flags attribute set (or more precisely is used for bit operations) ?

I want to be able to hit all cases in a switch that matche

9条回答
  •  旧时难觅i
    2021-01-31 14:44

    The easiest way is to just perform an ORed enum, in your case you could do the following :

    [Flags()]public enum CheckType
    {
        Form = 1,   
        QueryString = 2,
        TempData = 4,
        FormQueryString = Form | QueryString,
        QueryStringTempData = QueryString | TempData,
        All = FormQueryString | TempData
    }
    

    Once you have the enum setup its now easy to perform your switch statement.

    E.g, if i have set the following :

    var chkType = CheckType.Form | CheckType.QueryString;
    

    I can use the following switch statement as follows :

    switch(chkType){
     case CheckType.Form:
       // Have Form
     break;
     case CheckType.QueryString:
       // Have QueryString
     break;
     case CheckType.TempData:
      // Have TempData
     break;
     case CheckType.FormQueryString:
      // Have both Form and QueryString
     break;
     case CheckType.QueryStringTempData:
      // Have both QueryString and TempData
     break;
     case CheckType.All:
      // All bit options are set
     break;
    }
    

    Much cleaner and you don't need to use an if statement with HasFlag. You can make any combinations you want and then make the switch statement easy to read.

    I would recommend breaking apart your enums, try see if you are not mixing different things into the same enum. You could setup multiple enums to reduce the number of cases.

提交回复
热议问题