[英]I have a C# switch and I need to call a method before each case returns. Is there any way I could simplify this?
I have this code which I refactored to use a switch but it still looks very clumsy.我有这段代码,我将其重构为使用开关,但它看起来仍然很笨拙。 Now I am looking for a way to simplify it.
现在我正在寻找一种简化它的方法。
public async Task CheckAvailability()
{
switch (Settings.Mode)
{
case Enums.MO.Learn:
if (await IsLearn())
{
await ShowFirstMessageAsync();
return;
}
break;
case Enums.MO.Practice:
if (await IsPractice())
{
await ShowFirstMessageAsync();
return;
}
break;
case Enums.MO.Quiz:
if (await IsQuiz())
{
await ShowFirstMessageAsync();
return;
}
break;
default:
break;
}
await PickCard();
}
Is there anyone that can think of a simpler way to implement this without the need for multiple calls to await ShowFirstMessageAsync?有没有人可以想出一种更简单的方法来实现这一点,而无需多次调用 await ShowFirstMessageAsync?
This is a good opportunity to use switch
expressions in C# 8:这是在 C# 8 中使用
switch
表达式的好机会:
var shouldShowFirstMessage = Settings.Mode switch
{
Enums.MO.Learn => await IsLearn(),
Enums.MO.Practice => await IsPractice(),
Enums.MO.Quiz => await IsQuiz(),
_ => false
}
if (shouldShowFirstMessage) {
await ShowFirstMessageAsync();
} else {
await PickCard();
}
Maybe this:也许是这样:
public async Task CheckAvailability()
{
bool showFirstMessage = false;
switch (Settings.Mode)
{
case Enums.MO.Learn:
showFirstMessage = await IsLearn();
break;
case Enums.MO.Practice:
showFirstMessage = await IsPractice();
break;
case Enums.MO.Quiz:
showFirstMessage = await IsQuiz();
break;
default:
break;
}
if (showFirstMessage)
{
await ShowFirstMessageAsync();
return;
}
await PickCard();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.