When is a custom enumeration / collection useful?

I discard this line after visiting various websites in order to try to understand an example of using a real-time user enumeration. I have some examples. But they lead me to confusion.

Example

Take 1

class NumberArray
{
    public int[] scores;

    public NumberArray()
    {
    }

    public NumberArray(int[] scores)
    {
        this.scores = scores;
    }

    public int[] Scores
    {
        get {return scores;}
    }

}

Take 2

public class Enumerator : IEnumerator
{
    int[] scores;
    int cur;
    public Enumerator(int[] scores)
    {
        this.scores = scores;
        cur = -1;
    }
    public Object Current
    {
        get {
            return scores[cur];
        }
    }

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

    public bool MoveNext()
    {
        cur++;
        if (cur < scores.Length)
            return true;
        else return false;
    }
}

public class Enumerable : IEnumerable
{
    int[] numbers;

    public void GetNumbersForEnumeration(int[] values)
    {
        numbers = values;
        for (int i = 0; i < values.Length; i++)
            numbers[i] = values[i];
    }

    public IEnumerator GetEnumerator()
    {
        return new Enumerator(numbers);
    }
}

home

static void Main()
{
    int[] arr = new int[] { 1, 2, 3, 4, 5 };
    NumberArray num = new NumberArray(arr);
    foreach(int val in num.Scores)
    {
        Console.WriteLine(val);
    }

    Enumerable en = new Enumerable();
    en.GetNumbersForEnumeration(arr);

    foreach (int i in en)
    {
        Console.WriteLine(i);
    }
    Console.ReadKey(true);
}

In take 2, I performed a user iteration to iterate over the same array of integers as in take 1. Why should I beat the bushes to iterate an integer using user iteration ?

, . , ? ( , , ).

: - . , , , , .

+3
3

, , , , . , LINQ to SQL, - :

foreach(var employee in dataContext.Employees) {
    // Process employee
}

foreach Employees . , , , .

. : . foreach. ( .NET Framework 4 ​​ ).

+6

, , , ( take 1) ( 2), ,

. ( , ). , , . , , (, , , , ).

, # 2 IEnumerable . . - yield?

+3

Just like another example, when user iteration has been useful to me in the past, it was to provide a general abstraction to recursively list all the nodes in the tree structure ...

foreach (Node n in tree)
  //...do something
+2
source

Source: https://habr.com/ru/post/1720667/


All Articles