Restart a foreach loop in C#?

前端 未结 5 1220
傲寒
傲寒 2021-02-07 04:02

How can I restart a foreach loop in C#??

For example:

Action a;
foreach(Constrain c in Constrains)
{
   if(!c.Allows(a))
   {
      a.Change         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 04:29

    Although a very old thread - none of the answers paid due attention to the semantics of that code:

    • You have a chain of constraints on a
    • If a breaks any of them, try another a and push that through the chain.

    That is, a.Change() should be separated from the constraint checking loop, also adhering to the CQS principle:

    while (!MeetsConstraints(a))
    {
        a.Change();
    }
    
    bool MeetsConstraints(Thing a)
    {
        return Constraints.All(c => c.Allows(a));
    }
    

    No goto, no ugly loops, just simple and clean.

提交回复
热议问题