Combine return and switch(组合返回和切换)
问题描述
如何组合 return 和 switch 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.
switch 和 return 不能这样组合,因为 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";
这篇关于组合返回和切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:组合返回和切换
 
				
         
 
            
        基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				