递归条件 - 最佳实践
打破循环的最佳做法是什么? 我的想法是:
Child Find(Parent parent, object criteria)
{
Child child = null;
foreach(Child wannabe in parent.Childs)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
if (child != null) break;
}
return child;
}
或者
Child Find(Parent parent, object criteria)
{
Child child = null;
var conditionator = from c in parent.Childs where child != null select c;
foreach(Child wannabe in conditionator)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
}
return child;
}
或者
Child Find(Parent parent, object criteria)
{
Child child = null;
var enumerator = parent.Childs.GetEnumerator();
while(child != null && enumerator.MoveNext())
{
if (enumerator.Current.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
}
return child;
}
你觉得怎么样,有更好的想法吗? 我正在寻找最好的解决方案:D
mo
what's the best practise to break a loop?
my ideas were:
Child Find(Parent parent, object criteria)
{
Child child = null;
foreach(Child wannabe in parent.Childs)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
if (child != null) break;
}
return child;
}
or
Child Find(Parent parent, object criteria)
{
Child child = null;
var conditionator = from c in parent.Childs where child != null select c;
foreach(Child wannabe in conditionator)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
}
return child;
}
or
Child Find(Parent parent, object criteria)
{
Child child = null;
var enumerator = parent.Childs.GetEnumerator();
while(child != null && enumerator.MoveNext())
{
if (enumerator.Current.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
}
return child;
}
what do u think, any better ideas?
i'm looking for the niciest solution :D
mo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Linq 可能更简洁,但也更难理解!
Linq may be more terse, but can be more difficult to understand!
您无需自己处理
IEnumerator
,因此选项 3 已不再适用。选项 2 不起作用。无论是否找到匹配项,它都会继续,如果最后一个子项不是匹配项且其子项不包含匹配项,则即使之前存在匹配项,结果也将为
null
。假设您反对多个
return
语句,选项 1 似乎是最干净的。There's no need for you to deal with the
IEnumerator
yourself, so option 3 is out.Option 2 does not function. It continues regardless of finding a match, and if the last child is not a match and its children do not contain a match, then the result will be
null
even if there was a prior match.Option 1 seems the cleanest, assuming you object to multiple
return
statements.