使用匿名委托时如何退出 List<string>.ForEach 循环?

How do i exit a Listlt;stringgt;.ForEach loop when using an anonymous delegate?(使用匿名委托时如何退出 Listlt;stringgt;.ForEach 循环?)

本文介绍了使用匿名委托时如何退出 List<string>.ForEach 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在正常循环中,您可以使用 break 跳出循环.使用匿名委托也可以做到这一点吗?

In a normal loop you can break out of a loop using break. Can the same be done using an anonymous delegate?

示例inputString 和 result 都在委托之外声明.

Example inputString and result are both declared outside the delegate.

blackList.ForEach(new Action<string>(
    delegate(string item)
    {
        if(inputString.Contains(item)==true)
        {
            result = true;
            // I want to break here
        }
    }
));

感谢您的回复,我实际上正在阅读您的书 John :) 只是为了记录,我遇到了这个问题并切换回正常的 foreach 循环,但我发布了这个问题,看看我是否遗漏了什么.

Thanks for the replies, I'm actually reading your book at the minute John :) Just for the record i hit this issue and switched back to a normal foreach loop but I posted this question to see if i missed something.

推荐答案

正如其他人所发布的,您无法在 ForEach 中退出循环.

As others have posted, you can't exit the loop in ForEach.

你会使用 LINQ 吗?如果是这样,您可以轻松地结合 TakeWhile 和自定义 ForEach 扩展方法(现在几乎每个项目似乎都有).

Are you able to use LINQ? If so, you could easily combine TakeWhile and a custom ForEach extension method (which just about every project seems to have these days).

但是,在您的示例中,List<T>.FindIndex 将是最好的选择 - 但如果您实际上并没有这样做,请发布您真正想要做的示例.

In your example, however, List<T>.FindIndex would be the best alternative - but if you're not actually doing that, please post an example of what you really want to do.

这篇关于使用匿名委托时如何退出 List&lt;string&gt;.ForEach 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用匿名委托时如何退出 List&lt;string&gt;.ForEach 循环?

基础教程推荐