gpt4 book ai didi

C# Switch If 条件来扩展 switch case

转载 作者:行者123 更新时间:2023-12-03 18:17:17 28 4
gpt4 key购买 nike

我有一些数据需要转换,为此我需要一个超过 50 个案例的切换条件,我需要 3 次相同的案例,但在第三次我需要 50 个案例和一些更多,我不想写两次相同的代码。也许有可能做这样的事情。

switch (example)
{
case "1":
//do something
case "2":
//do something
case "50":
//do something
//now maybe something like this
if (condition == true)
{
case "1":
//do something else than above at case "1", and so on
//now its i little bit illogical, but i neet to do the first 50 cases and then
//use the cases 1 to 50 again but with other actions
}
}

最佳答案

从 C# 7 开始,您可以组合 the case statement with when clause并使用它来稍微简化您的代码

switch (example)
{
case "1":
//do something
case "2":
//do something
case "50":
//do something
//now maybe something like this
case "51" when condition == true:
//do something, and so on
default:
break;
}

Starting with C# 7.0, because case statements need not be mutually exclusive, you can add a when clause to specify an additional condition that must be satisfied for the case statement to evaluate to true. The when clause can be any expression that returns a Boolean value.

关于C# Switch If 条件来扩展 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60316019/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com