我如何打破if语句?
退出仅适用于“for”,“sub”等。
在VB.net中:
if i > 0 then
do stuff here!
end if
在C#中:
if (i > 0)
{
do stuff here!
}
你不能“突破”if语句。如果您正在尝试这个,那么您的逻辑是错误的,并且您正在从错误的角度接近它。
您尝试实现的一个示例将有助于澄清,但我怀疑您正在构建它错误。
没有这样的等价物,但你真的不需要使用If语句。您可能希望查看使用Select Case(VB)或Switch(C#)语句。
您可以使用
bool result = false;
if (i < 10)
{
if (i == 7)
{
result = true;
break;
}
}
return result;
我不得不承认,在某些情况下,你真的想要一个像退出子或休息的东西。在极少数情况下,我使用“Goto End”并使用def跳过“End If”。结束:
我知道这是一个老帖子,但我一直在寻找相同的答案,最后我想出来了
try{
if (i > 0) // the outer if condition
{
Console.WriteLine("Will work everytime");
if (i == 10)//inner if condition.when its true it will break out of the outer if condition
{
throw new Exception();
}
Console.WriteLine("Will only work when the inner if is not true");
}
}
catch (Exception ex)
{
// you can add something if you want
}
`