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";
这篇关于组合返回和切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:组合返回和切换
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
