[英]How can I use 'continue' and `break` in an extension method?
我已經定義了以下擴展方法:
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
});
我希望能夠利用continue
和break
我的擴展方法,以便我可以這樣做:
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
});
這些關鍵字只能在for
, foreach
, while
或do-while
循環中使用嗎?
這些關鍵字只能在for,foreach,while循環中使用嗎?
是。 這些語句僅限於循環類型。 正如文檔所說 :
continue語句將控制權傳遞給封閉的while,do,for或foreach語句的下一次迭代。
而且 :
break語句終止它出現的最近的封閉循環或switch語句 。 控制權將傳遞給終止語句后面的語句(如果有)。
我建議你使用一個常規的foreach
,它是自我表達的。 我認為任何在ForEach
擴展方法中語義使用它們的嘗試都會產生比使用常規循環更奇怪的代碼。
我的意思是,這不簡單嗎?:
var arr = new [] {1, 2, 3}
foreach (int number in arr)
{
if(n == 1) { continue; }
if(n == -1) { break; }
}
除了Yuval的回答之外,我還想補充一點,你可以按如下方式實現:
將Action<T>
更改為Func<T, bool>
,它接受一個T
參數並返回一個bool
結果。
通過在條件上從函數返回來容易地處理“繼續”情況,從而繼續循環的下一次迭代。
可以通過從函數返回bool
來處理“break”情況,該函數指示是否繼續:
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;
});
是的,這些關鍵字僅限於while
, do
, for
和foreach
(如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
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.