Is foreach purely “syntactic sugar”?

前端 未结 5 1406
南旧
南旧 2020-12-06 10:32

The compiler compiles a foreach loop into something like a for loop when the foreach is used with an array. And the compiler compile

5条回答
  •  时光说笑
    2020-12-06 11:07

    Yes, it is purely sugar. The following code

    var MyList = new List() { 10 , 20 , 30 , 40, 50} ;  
    foreach(int i in MyList) 
    {
        Console.WriteLine(i);
    }
    

    is translated in compiler as:

    Ienumrator rator = MyList.GetEnumrator();
    
    try
    {
       while(rator.MoveNext())
       {
           int i = rator.Current; 
           Console.WriteLine(i); 
       }
    }
    finally
    {
        rator.Dispose()
    }
    

提交回复
热议问题