Will C # benefit from differences between types of counters such as C ++ iterators?

I was thinking of a method IEnumerator.Reset(). I read in the MSDN documentation that it is only there for COM interoperability. As a C ++ programmer, it seems to me that IEnumeratorwhich supports Reset, I would call forward iterator , and IEnumeratorwhich does not support Reset, is actually an input iterator .

So, the first part of my question is: is this understanding right?

The second part of my question is whether there would be any benefit in C # if there was a difference between input iterators and forward iterators (or, if you want, "enumerators")? Does this not help to eliminate some confusion among programmers, for example, found in this question about cloning iterators ?

EDIT: Clarification on input and input iterators. The input iterator only ensures that you can list the elements of a collection (either from a generator function or an input stream) only once. This is how IEnumerator works in C #. Regardless of whether it is possible to list a second time, it is determined whether it is supported Reset. A promising iterator does not have this limitation. You can list members as often as you want.

Some C # programmers do not underestimate why IEnumeratorthey cannot be reliably used in a multi-pass algorithm. Consider the following case:

void PrintContents(IEnumerator<int> xs)
{
  while (iter.MoveNext())
    Console.WriteLine(iter.Current); 
  iter.Reset();
  while (iter.MoveNext())
    Console.WriteLine(iter.Current); 
}

If in this context we will call PrintContents, no problem:

List<int> ys = new List<int>() { 1, 2, 3 }
PrintContents(ys.GetEnumerator()); 

However, look at the following:

IEnumerable<int> GenerateInts() {   
  System.Random rnd = new System.Random();
  for (int i=0; i < 10; ++i)
    yield return Rnd.Next();
}

PrintContents(GenerateInts());

If a supported IEnumerator Reset, in other words, supported multi-pass algorithm, then every time you repeat it, it will be different. That would be undesirable because it would be awesome behavior. This example is a bit fake, but it does occur in the real world (for example, reading from file streams).

+5
source share
5 answers

. , , , # . .

++ - . # , ( ). , , , , / . , - , , ++.

, .

++ , . , . , , , . .

# . , , .

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

.

+2

Reset . Reset. , , " " " " .NET, IEnumerable<T> IEnumerator<T>.

. , Microsoft Eric Lippert ( capactiy, , , - , , ) . . .

+3

#:

IEnumerator . foreach, IEnumerable.

IEnumerable _myCollection;
...
foreach (var item in _myCollection) { /* Do something */ }

IEnumerator. , , IEnumerable. IEnumerable , IEnumerator, ( ).

Reset() IEnumerator, , ( ) .

+1

.NET , IEnumerator<T> , , , promises. IEnumerable<T>, , , ReadOnlyCollection, .

, , IEnumerable<T>, ( , ), , ( ), ReadOnlyCollection<T> , , , . IEnumerable<T>, .

+1

. IEnumerable . . foreach, .

: ( ) ( - ) , . , . #.

IList<T>, .

-1

All Articles