Wil*_*lsu 1 c# loops switch-statement
所以我有一些如下所示的 C# 代码:
while(condition)
{
switch(anumber)
{
case 0:
//do something
break;
case 1:
//do something
break;
//and so on
}
}
Run Code Online (Sandbox Code Playgroud)
作为一名编程新手,我最近将关键字添加到continue了我的词汇表中。经过一些研究后,我发现了这一点:
continue 语句与封闭循环相关
所以我的代码也应该像这样工作:
while(condition)
{
switch(anumber)
{
case 0:
//do something
continue;
//and so on
}
}
Run Code Online (Sandbox Code Playgroud)
但编写不产生编译器错误的代码并不是一切。continue在循环封闭的开关块中使用是一个好主意吗?例如,在性能方面是否有任何差异,或者这只是两种语法上不同但在其他方面非常相似的方法来实现相同的结果?
如果 switch 之后还有一些代码行, continue 关键字将忽略它们。试试这个,你会看到不同的:
while(condition)
{
switch(anumber)
{
case 0:
//do something
break;
case 1:
//do something
break;
//and so on
}
Console.WriteLine("it's a message");
}
Run Code Online (Sandbox Code Playgroud)
和
while(condition)
{
switch(anumber)
{
case 0:
//do something
continue;
case 1:
//do something
continue;
//and so on
}
Console.WriteLine("it's a message");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1486 次 |
| 最近记录: |