Usage of C# foreach

 foreach is a syntactic sugar used to simplify code iterating over enumerable elements. The traversed class implements the traversal function by implementing the IEnumerable interface and a related IEnumerator enumerator.

There are two restrictions in the foreach statement, the first is not to modify the enumeration members, and the second is not to delete the collection. That is, both of the following methods are wrong.

        // Use "foreach" to loop an arraylist
        foreach( int i in arrInt )
        {
            i++;//Can't be compiled
            Debug.WriteLine( i.ToString() );
        }
 
        // Use "foreach" to loop an arraylist
        foreach( int i in arrInt )
        {
            arrInt.Remove( i );//It will generate error in run-time
            Debug.WriteLine( i.ToString() );
        }

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestForeach : MonoBehaviour
{
    void Start()
    {
        GoTestForeach();
    }

    private void GoTestForeach()
    {
        
        Debug.Log("start foreach 空数组的遍历"); 
        var array = new List<string>();
        //注意区分:空数组是指元素个数为0,数组为空是指数组变量本身为null
        
        foreach(var item in array)
        {
            //这里数组array变量不为空,只是元素个数为0,在遍历时不会报空。
            Debug.Log(item);
        }

        //foreach语句中不能修改枚举成员
        var array2 = new List<string> { "", "1", "2", "3" };
        foreach(var item in array2)
        {
            Debug.Log(item);
            array2.Remove("1");
            Debug.Log(item);
        }

    }

}

 Then for the above two operations, you can use for to implement. In addition, let me say a word here, that is, the problem of deleting multiple data in a recordset is also a place where problems often occur (similar questions are often asked on the forum), because in some When deleting a record set, the corresponding index has also changed after the delete operation. At this time, the deletion should be reversed, and the general form is as follows.

        // Use "for" to loop an arraylist
        for( int i = arrInt.Count - 1; i >=0; i-- )
        {
            int n = ( int ) arrInt[i];
            if( n == 5 )
                arrInt.RemoveAt( i ); // Remove data here
            Debug.WriteLine( n.ToString() );
        }
 

Except for these two places, foreach can basically be applied to any loop
 

IEnumerator, IEnumerable enumerator interface_Peter_Gao_'s blog-CSDN blog
https://blog.csdn.net/hc1104/article/details/8130818

Guess you like

Origin blog.csdn.net/qq_42672770/article/details/122862970