组合返回和切换 [英] Combine return and switch

查看:30
本文介绍了组合返回和切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何组合 returnswitch case 语句?

How can I combine return and switch case statements?

我想要类似的东西

return switch(a)
       {
          case 1:"lalala"
          case 2:"blalbla"
          case 3:"lolollo"
          default:"default" 
       };

我知道这个解决方案

switch(a)
{
    case 1: return "lalala";
    case 2: return "blalbla";
    case 3: return "lolollo";
    default: return "default";
}

但我只想使用 return 运算符.

But I want to only use the return operator.

推荐答案

注意:从 C#8 开始(十年后!)现在可以实现了,请看答案 下方.

Note: As of C#8 (ten years later!) this is now possible, please see the answer below.

switchreturn 不能这样组合,因为 switch 是一个 statement,而不是 表达式(即不返回值).
如果你真的想只使用一个 return,你可以制作一个 Dictionary 来将 switch 变量映射到返回值:

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<int, string>() 
{
    {1, "lala"}, 
    {2, "lolo"}, 
    {3, "haha"}, 
};
string output;
return map.TryGetValue(a, out output) ? output : "default";

这篇关于组合返回和切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆