Evaluate Expressions in Switch Statements in C#

前端 未结 12 468
抹茶落季
抹茶落季 2021-01-31 01:42

I have to implement the following in a switch statement:

switch(num)
{
  case 4:
    // some code ;
    break;
  case 3:
    // some code ;
    brea         


        
12条回答
  •  孤独总比滥情好
    2021-01-31 02:26

    What you could do is to use a delegate like this.

            var actionSwitch = new Dictionary, Action>
            {
                 { x => x < 0 ,     () => Log.Information("less than zero!")},
                 { x => x == 1,     () => Log.Information("1")},
                 { x => x == 2,     () => Log.Information("2")},
                 { x => x == 3,     () => Log.Information("3")},
                 { x => x == 4,     () => Log.Information("4")},
                 { x => x == 5,     () => Log.Information("5")},
            };
    
            int numberToCheck = 1;
    
            //Used like this
            actionSwitch.FirstOrDefault(sw => sw.Key(numberToCheck)).Value();
    

    Just swap out what you wan´t to perform where the Log.Information("x") is and you have your "switch" statement.

    You will need to some error handling if you check for a key that is "found" by the Func.

    If you like to see the Func version of the switch I just wrote a blog post with Switch example chapter.

    But if you can use C# 7 it will give you better switch capabilities.

提交回复
热议问题