[英]How can I use the return value of a C# switch statement to exit a Task with a true or false?
I have this code:我有这个代码:
public async Task PickCard()
{
switch (Settings.Co)
{
case CO.Random: Random(); break;
case CO.FirstToLast: ArrangeCardOrder(true); break;
case CO.LastToFirst: ArrangeCardOrder(false); break;
}
await ShowCard();
}
I am going to be modifying Random()
, ArrangeCardOrder(true)
and ArrangeCardOrder(false)
to return a true
or false
.我将修改
Random()
、 ArrangeCardOrder(true)
和ArrangeCardOrder(false)
以返回true
或false
。
Is there a way that I can get that information from the switch and if they methods return true
then call await ShowCard
and then exit PickCard with a true and if the methods return false
, simply exit PickCard with a false
?有没有办法可以从 switch 中获取该信息,如果它们的方法返回
true
然后调用await ShowCard
然后以 true 退出 PickCard 并且如果这些方法返回false
,只需以false
退出 PickCard ?
Currently that's just a switch statement .目前这只是一个 switch语句。 To use a switch expression you need to change the syntax a bit - as well as using C# 8. You'll also want to change the return type so that
PickCard
can indicate the result.要使用 switch表达式,您需要稍微更改语法 - 以及使用 C# 8。您还需要更改返回类型,以便
PickCard
可以指示结果。
public async Task<bool> PickCard()
{
// This is a switch *expression* instead of a switch *statement*.
// Switch expressions were introduced in C# 8.
bool result = Settings.Co switch
{
CO.Random => Random(),
CO.FirstToLast => ArrangeCardOrder(true),
CO.LastToFirst => ArrangeCardOrder(false),
// Adjust for whatever you want to do
_ => throw new InvalidOperationException("Invalid setting")
}
if (result)
{
await ShowCard();
}
return result;
}
Something like this?像这样的东西? Can obviously be adjusted to fit your exact needs better...
显然可以调整以更好地满足您的确切需求......
var succeeded = false;
switch (Settings.Co)
{
case CO.Random:
succeeded = Random();
break;
(...)
}
var result = false;
if(succeeded){
result = await ShowCard();
// or alternatively:
// await ShowCard();
// return true;
}
return result;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.