与此问题相关
假设我有一个很长的方法,我想在某些条件下中止.最好的方法是什么?以下是我能想到的两种方式.
try
{
// if i is 0, we don't want to continue
int i = testi();
if(i == 0)
throw new StopException("stop")
// the rest of our code
}
catch(StopException stop)
{
// handle our stop exception
}
catch{
// everything else
}
Run Code Online (Sandbox Code Playgroud)
这是另一个
bool go = true
while(go)
{
// if i is 0, we don't want to continue
int i = testi();
if(i == 0)
{
go = false;
break;
}
// the rest of our code
}
Run Code Online (Sandbox Code Playgroud)
这两个看起来都很笨拙.抛出异常似乎有点矫枉过正,我实际上并不想循环任何东西,因此while被滥用.在我看来应该(并且可能是)在C#中更优雅的方式吗?
DOY.我实际上已经使用过很多次了,出于某种原因,它今天突然出现了.谢谢你沉溺于我的愚蠢
中断C#方法的标准方法是简单地使用该return语句.
如果方法是无效的return,如果不是那么return null或return 0取决于案例.
绝对不需要抛出和异常而不是返回.