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";
这篇关于组合返回和切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:组合返回和切换


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01