Alternative for switch that only calls methods based on cases values

后端 未结 4 576
醉话见心
醉话见心 2021-01-19 03:59

Is there a possible way to write the next switch in some shorter, readable code?

switch (SomeValue)
{
  case \"001\": return DoMethod1(); break;
  case \"002         


        
4条回答
  •  孤独总比滥情好
    2021-01-19 04:42

    I use a Mapping extension for that. This way yoy can use the following syntax:

        return SomeValue
        .Map("001", DoMethod1)
        .Map("002", DoMethod2)
         //etc
    

    This makes it also possible to do this:

        return SomeValue
        .Map(1, DoMethod1)
        .Map(2, DoMethod2)
        .Map(x => x < 0, DoMethod3)
        .Map(x => x > 5  && x < 10, DoMethod4)
        .Else(4); // a simple value of a method
    

提交回复
热议问题