Combine return and switch

后端 未结 12 2065
长情又很酷
长情又很酷 2021-02-03 22:15

How can I combine return and switch case statements?

I want something like

return switch(a)
       {
          case 1:\"lalala         


        
12条回答
  •  醉话见心
    2021-02-03 22:34

    switch and return can't combine that way, because switch is a statement, not an expression (i.e., it doesn't return a value).
    If you really want to use just a single return, you could make a Dictionary to map the switch variable to return values:

    var map = new Dictionary() 
    {
        {1, "lala"}, 
        {2, "lolo"}, 
        {3, "haha"}, 
    };
    string output;
    return map.TryGetValue(a, out output) ? output : "default";
    

提交回复
热议问题