我可以不使用 break; 来使用 switch 语句吗?
Can I use a switch statement without break;?
我的老师不允许我们使用 break、goto、continue...等
我决定在我的代码中添加一个 switch 语句,但我卡住了,因为让它工作的唯一方法是这样的:
switch (exitValidation)
{
case 'y':
case 'Y': exit = false; break;
case 'n':
case 'N': Console.WriteLine("\nPlease Enter Valid values");
exit = false; break;
default: exit = true; break;
}
有没有办法在没有"break;"的情况下使用switch?
另外,使用 "break;" 真的那么糟糕吗?
首先,你的老师要么被误导了,要么你听错了。在 switch
语句中使用 break
是完全可以接受的,实际上是 specified in the documentation,如果不存在,将导致编译错误。
但是,您可以在 switch 语句中使用 return
来达到几乎相同的效果。但它当然会 return switch
所在的整个方法。
例如:
switch(exitValidation)
{
case 'y':
case 'Y':
return false;
case 'n':
case 'N':
return true;
}
一个解决方案是将开关提取到一个方法中并使用其 return 值:
public bool EvaluateSwitch(int exitValidation)
{
switch (exitValidation)
{
case 'y':
case 'Y': return false;
case 'n':
case 'N': Console.WriteLine("\nPlease Enter Valid values");
return false;
default: return true;
}
}
正因为我讨厌那些仅仅因为听说他们“不好”而限制使用正确语句的老师,这里有一个不间断的解决方案,你的老师会讨厌,但必须接受:
using static System.Console;
var exit = char.ToUpper(exitValidation) switch {
'Y' => false,
'N'=> new Func<bool>(() => { WriteLine("\nPlease Enter Valid values"); return false; })(),
_ => true
};
我的老师不允许我们使用 break、goto、continue...等 我决定在我的代码中添加一个 switch 语句,但我卡住了,因为让它工作的唯一方法是这样的:
switch (exitValidation)
{
case 'y':
case 'Y': exit = false; break;
case 'n':
case 'N': Console.WriteLine("\nPlease Enter Valid values");
exit = false; break;
default: exit = true; break;
}
有没有办法在没有"break;"的情况下使用switch? 另外,使用 "break;" 真的那么糟糕吗?
首先,你的老师要么被误导了,要么你听错了。在 switch
语句中使用 break
是完全可以接受的,实际上是 specified in the documentation,如果不存在,将导致编译错误。
但是,您可以在 switch 语句中使用 return
来达到几乎相同的效果。但它当然会 return switch
所在的整个方法。
例如:
switch(exitValidation)
{
case 'y':
case 'Y':
return false;
case 'n':
case 'N':
return true;
}
一个解决方案是将开关提取到一个方法中并使用其 return 值:
public bool EvaluateSwitch(int exitValidation)
{
switch (exitValidation)
{
case 'y':
case 'Y': return false;
case 'n':
case 'N': Console.WriteLine("\nPlease Enter Valid values");
return false;
default: return true;
}
}
正因为我讨厌那些仅仅因为听说他们“不好”而限制使用正确语句的老师,这里有一个不间断的解决方案,你的老师会讨厌,但必须接受:
using static System.Console;
var exit = char.ToUpper(exitValidation) switch {
'Y' => false,
'N'=> new Func<bool>(() => { WriteLine("\nPlease Enter Valid values"); return false; })(),
_ => true
};