Maison  >  Article  >  développement back-end  >  Explication détaillée du principe d'implémentation de foreach en C#

Explication détaillée du principe d'implémentation de foreach en C#

黄舟
黄舟original
2017-10-05 15:32:091758parcourir

Cet article présente principalement en détail le principe d'implémentation de foreach en C#, qui a une certaine valeur de référence. Les amis intéressés peuvent s'y référer

Cet article enregistre principalement mon étude du principe de traversée foreach en C#.

Le déplacement d'éléments dans une collection est une opération souvent impliquée dans tout codage, c'est pourquoi la plupart des langages de programmation ont écrit ce processus dans la grammaire, comme foreach en C#. Vous verrez souvent le code de traversée suivant :


var lstStr = new List<string> { "a", "b" };
   foreach (var str in lstStr)
      {
        Console.WriteLine(str);
      }

Le processus d'exécution réel de ce code :


var lstStr = new List<string> {"a", "b"};
   IEnumerator<string> enumeratorLst = lstStr.GetEnumerator();
   while (enumeratorLst.MoveNext())
      {
        Console.WriteLine(enumeratorLst.Current);
      }

Vous trouverez la méthode GetEnumerator() et le type IEnumerator98c455a79ddfebb79781bff588e7b37e qui fait intervenir les notions de types énumérables et d'énumérateurs.

Pour faciliter la compréhension, voici un exemple non générique :


// 摘要:
//   公开枚举器,该枚举器支持在非泛型集合上进行简单迭代。
  public interface IEnumerable
  {
    // 摘要:
    //   返回一个循环访问集合的枚举器。
    //
    // 返回结果:
    //   可用于循环访问集合的 System.Collections.IEnumerator 对象。
    IEnumerator GetEnumerator();
  }

Une classe qui implémente cette interface est appelée une type enumerable, est un indicateur qui peut être parcouru en utilisant foreach.

La valeur de retour de la méthode GetEnumerator() est un énumérateur, qui peut être compris comme un curseur.


// 摘要:
//   支持对非泛型集合的简单迭代。
  public interface IEnumerator
  {
    // 摘要:
    //   获取集合中的当前元素。
    //
    // 返回结果:
    //   集合中的当前元素。
    //
    // 异常:
    //  System.InvalidOperationException:
    //   枚举数定位在该集合的第一个元素之前或最后一个元素之后。
    object Current { get; }

    // 摘要:
    //   将枚举数推进到集合的下一个元素。
    //
    // 返回结果:
    //   如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false。
    //
    // 异常:
    //  System.InvalidOperationException:
    //   在创建了枚举数后集合被修改了。
    bool MoveNext();
    //
    // 摘要:
    //   将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
    //
    // 异常:
    //  System.InvalidOperationException:
    //   在创建了枚举数后集合被修改了。
    void Reset();
  }

Ce qui suit est un exemple de personnalisation d'un itérateur (https://msdn.microsoft.com/en-us/library/system.collections .ienumerator.aspx) :


using System;
using System.Collections;

// Simple business object.
public class Person
{
  public Person(string fName, string lName)
  {
    this.firstName = fName;
    this.lastName = lName;
  }

  public string firstName;
  public string lastName;
}

// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
  private Person[] _people;
  public People(Person[] pArray)
  {
    _people = new Person[pArray.Length];

    for (int i = 0; i < pArray.Length; i++)
    {
      _people[i] = pArray[i];
    }
  }

// Implementation for the GetEnumerator method.
  IEnumerator IEnumerable.GetEnumerator()
  {
    return (IEnumerator) GetEnumerator();
  }

  public PeopleEnum GetEnumerator()
  {
    return new PeopleEnum(_people);
  }
}

// When you implement IEnumerable, you must also implement IEnumerator.
public class PeopleEnum : IEnumerator
{
  public Person[] _people;

  // Enumerators are positioned before the first element
  // until the first MoveNext() call.
  int position = -1;

  public PeopleEnum(Person[] list)
  {
    _people = list;
  }

  public bool MoveNext()
  {
    position++;
    return (position < _people.Length);
  }

  public void Reset()
  {
    position = -1;
  }

  object IEnumerator.Current
  {
    get
    {
      return Current;
    }
  }

  public Person Current
  {
    get
    {
      try
      {
        return _people[position];
      }
      catch (IndexOutOfRangeException)
      {
        throw new InvalidOperationException();
      }
    }
  }
}

class App
{
  static void Main()
  {
    Person[] peopleArray = new Person[3]
    {
      new Person("John", "Smith"),
      new Person("Jim", "Johnson"),
      new Person("Sue", "Rabon"),
    };

    People peopleList = new People(peopleArray);
    foreach (Person p in peopleList)
      Console.WriteLine(p.firstName + " " + p.lastName);

  }
}

/* This code produces output similar to the following:
 *
 * John Smith
 * Jim Johnson
 * Sue Rabon
 *
 */

Avec le mot-clé rendement, nous pouvons créer un énumérateur de cette manière :


using System;
using System.Collections;

// Simple business object.
public class Person
{
  public Person(string fName, string lName)
  {
    this.firstName = fName;
    this.lastName = lName;
  }

  public string firstName;
  public string lastName;
}

// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
  private Person[] _people;

  public People(Person[] pArray)
  {
    _people = new Person[pArray.Length];

    for (int i = 0; i < pArray.Length; i++)
    {
      _people[i] = pArray[i];
    }
  }

  // Implementation for the GetEnumerator method.
  IEnumerator IEnumerable.GetEnumerator()
  {
    for (int i = 0; i < _people.Length; i++)
    {
      yield return _people[i];
    }
  }

}


class App
{
  static void Main()
  {
    Person[] peopleArray = new Person[3]
    {
      new Person("John", "Smith"),
      new Person("Jim", "Johnson"),
      new Person("Sue", "Rabon"),
    };

    People peopleList = new People(peopleArray);
    foreach (Person p in peopleList)
      Console.WriteLine(p.firstName + " " + p.lastName);
  }
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn