如何在扩展方法中使用'continue'和`break`?

时间:2015-07-16 13:01:30

标签: c# .net morelinq

我定义了以下扩展方法:

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
   foreach (T obj in sequence)
   { 
      action(obj); 
   } 
}

然后我可以将其用作:

new [] {1, 2, 3} // an IEnumerable<T>
.ForEach(n => 
{
  // do something 
});

我希望能够在我的扩展方法中利用continuebreak,以便我可以这样做:

new [] {1, 2, 3}
.ForEach(n => 
{
    // this is an overly simplified example
    // the n==1 can be any conditional statement
    // I know in this case I could have just used .Where
    if(n == 1) { continue; }
    if(n == -1) { break; }      
    // do something 
});

这些关键字只能在forforeachwhiledo-while循环中使用吗?

3 个答案:

答案 0 :(得分:7)

  

这些关键字只能在for,foreach,while循环中使用吗?

是。这些语句仅限于循环类型。 As the docs say

  

continue语句将控制传递给下一次迭代   附上 while,do,for或foreach 语句。

And

  

break语句终止最近的封闭循环或开关   出现的陈述。控制权传递给语句   如果有的话,请遵循终止的陈述。

我建议您使用常规foreach,这是一种自我表达。我认为任何在ForEach扩展方法中语义使用它们的尝试都会产生比使用常规循环更奇怪的代码。

我的意思是,这不简单吗?:

var arr = new [] {1, 2, 3}
foreach (int number in arr)
{
    if(n == 1) { continue; }      
    if(n == -1) { break; }      
}

答案 1 :(得分:3)

除了Yuval的回答之外,我还想补充一点可以实现如下所示的内容:

Action<T>更改为Func<T, bool>,其中T参数会返回bool个结果。

&#34;继续&#34; case可以通过在条件上从函数返回来轻松处理,从而继续循环的下一次迭代。

&#34;休息&#34;可以通过从函数返回bool来处理case,该函数指示是否继续:

public static void ForEach<T>(this IEnumerable<T> sequence, Func<T, bool> action)
{
  foreach (T obj in sequence)
  { 
    if (!action(obj)) 
      break;
  }
}

new [] {1, 2, 3}.ForEach(n => 
{
    if(n == 1) { return true;}      
    if(n == -1) { return false; }  

    // do something 
    ...
    return true;
});

答案 2 :(得分:1)

是的,这些关键字仅限于whiledoforforeach(引用Yuval)。

此代码与您提出的内容大致相同:

bool shouldBreak = false;

new [] {1, 2, 3}
.ForEach(n => 
{
    if (!shouldBreak)
    {
        if(n == 1) { /* no action */ }      
        else if(n == -1) { shouldBreak = true; }
        else
        {
            // do something 
        }
    }
});