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

后端 未结 9 2017
忘掉有多难
忘掉有多难 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条回答
  •  北海茫月
    2021-01-31 15:04

    Based on your edit and your real-life code, I'd probably update the IsValidForRequest method to look something like this:

    public sealed override bool IsValidForRequest
        (ControllerContext cc, MethodInfo mi)
    {
        _ControllerContext = cc;
    
        var map = new Dictionary>
            {
                { CheckType.Form, () => CheckForm(cc.HttpContext.Request.Form) },
                { CheckType.Parameter,
                    () => CheckParameter(cc.HttpContext.Request.Params) },
                { CheckType.TempData, () => CheckTempData(cc.Controller.TempData) },
                { CheckType.RouteData, () => CheckRouteData(cc.RouteData.Values) }
            };
    
        foreach (var item in map)
        {
            if ((item.Key & _CheckType) == item.Key)
            {
                if (item.Value())
                {
                    return true;
                }
            }
        }
        return false;
    }
    

提交回复
热议问题