本文介绍了列表ForEach中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法打破foreach扩展方法? break关键字不能将扩展方法识别为有效的作用域。

  //不能编译ForEach(i => {System.Windows.MessageBox.Show(i.ToString()); if(i> 2)break;}) ; 





$ b

编辑:从问题中删除linq p>




请注意代码只是一个示例,显示break在扩展方法中不起作用...我真正想要的是用户能够中止处理列表.. UI线程有一个中止变量和for循环只是当用户点击取消按钮时打破。现在,我有一个正常的循环,但我想看看是否有可能做的扩展方法。

解决方案

把这个称为 List< T> Foreach与LINQ之间可能更准确。



尽管如此,没有办法打破这个循环。主要是因为它实际上并不是一个循环。这是一个方法,它需要在循环内部调用一个委托。



创建一个具有中断能力的ForEach是非常直接的,但是

pre $ public delegate void ForEachAction< T>(T value,ref bool doBreak);
public static void ForEach< T>(this IEnumerable< T> enumerable,ForEachAction< T> action){
var doBreak = false;
foreach(var cur in enumerable){
action(cur,ref doBreak);
if(doBreak){
break;





你可以重写你的代码如下所示:

  Enumerable.Range(0,10)
.ForEach((int i,ref bool doBreak) => {
System.Windows.MessageBox.Show(i.ToString());
if(i> 2){doBreak = true;}
});


is there a way to break out of the foreach extension method? The "break" keyword doesn't recognize the extension method as a valid scope to break from.

//Doesn't compile
Enumerable.Range(0, 10).ToList().ForEach(i => { System.Windows.MessageBox.Show(i.ToString()); if (i > 2)break; });


Edit: removed "linq" from question


note the code is just an example to show break not working in the extension method... really what I want is for the user to be able to abort processing a list.. the UI thread has an abort variable and the for loop just breaks when the user hits a cancel button. Right now, I have a normal for loop, but I wanted to see if it was possible to do with the extension method.

解决方案

It's probably more accurate to call this a List<T> Foreach vs. a LINQ one.

In either case though no there is no way to break out of this loop. Primarily because it's not actually a loop per say. It's a method which takes a delegate that is called inside a loop.

Creating a ForEach with break capability is fairly straight forward though

public delegate void ForEachAction<T>(T value, ref bool doBreak);
public static void ForEach<T>(this IEnumerable<T> enumerable, ForEachAction<T> action) {
    var doBreak = false;
    foreach (var cur in enumerable) {
        action(cur, ref doBreak);
        if (doBreak) {
            break;
        }
    }
}

You could then rewrite your code as the following

Enumerable.Range(0,10)
    .ForEach((int i,ref bool doBreak) => {
        System.Windows.MessageBox.Show(i.ToString()); 
        if ( i > 2) {doBreak = true;}
    });

这篇关于列表ForEach中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 15:10