Combine return and switch

后端 未结 12 2057
长情又很酷
长情又很酷 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:38

    If you want switch to return value, you can use delegate:

    int a = 2;
    string result = new Func(delegate ()
    {
        switch (a)
        {
            case 1: return "lalala";
            case 2: return "blalbla";
            case 3: return "lolollo";
            default: return "default";
        }
    })();
    

    Or:

    int a = 2;
    string result = new Func(delegate (int i)
    {
        switch (i)
        {
            case 1: return "lalala";
            case 2: return "blalbla";
            case 3: return "lolollo";
            default: return "default";
        }
    })(a);
    

    Or just use lambda:

    int a = 2;
    string result = new Func((int i) =>
    {
        switch (i)
        {
            case 1: return "lalala";
            case 2: return "blalbla";
            case 3: return "lolollo";
            default: return "default";
        }
    })(a);
    

提交回复
热议问题