我如何在C#中实现for-else和foreach-else语句? [英] How do I implement for-else and foreach-else statement in C#?
本文介绍了我如何在C#中实现for-else和foreach-else语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
for(int i = 0;!connected&& i <100; i ++)
{
Thread.Sleep(1);
}
else throw new ConnectionError();
解决方案
foreach-else的Python构造如下所示:
foreach(elem in collection)
{
if(condition(elem))
打破;
}
else
{
doSomething();
$ b $ p
$ b 其他只在foreach循环中没有调用break的情况下执行
等价的AC#可能是:
$ p $ b $ found = false;
foreach(elem in collection)
{
if(condition(elem))
{
found = true;
break; (!找到)
{
doSomething();
I know they do not exist, but are there alternatives? Like this:
for (int i = 0; !connected && i < 100; i++)
{
Thread.Sleep(1);
}
else throw new ConnectionError();
解决方案
The Python Construct for foreach-else is like this:
foreach( elem in collection )
{
if( condition(elem) )
break;
}
else
{
doSomething();
}
The else only executes if break is not called during the foreach loop
A C# equivalent might be:
bool found = false;
foreach( elem in collection )
{
if( condition(elem) )
{
found = true;
break;
}
}
if( !found )
{
doSomething();
}
Source: The Visual C# Developer Center
这篇关于我如何在C#中实现for-else和foreach-else语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文