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

后端 未结 9 2019
忘掉有多难
忘掉有多难 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:01

    With C# 7 you can now write something like this:

    public void Run(CheckType checkType)
    {
        switch (checkType)
        {
            case var type when CheckType.Form == (type & CheckType.Form):
                DoSomething(/*Some type of collection is passed */);
                break;
    
            case var type when CheckType.QueryString == (type & CheckType.QueryString):
                DoSomethingElse(/*Some other type of collection is passed */);
                break;
    
            case var type when CheckType.TempData == (type & CheckType.TempData):
                DoWhatever(/*Some different type of collection is passed */);
                break;
        }
    }
    
    0 讨论(0)
  • 2021-01-31 15:02

    Should be possible in C# 7

    switch (t1)
        {
            case var t when t.HasFlag(TST.M1):
                {
                    break;
                }
            case var t when t.HasFlag(TST.M2):
                {
                    break;
                }
    
    0 讨论(0)
  • 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, Func<bool>>
            {
                { 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;
    }
    
    0 讨论(0)
提交回复
热议问题