IEnumerable and IEnumerator in C#

1. I do not understand what I mean when I read this:

    public class BinaryHeap<T> : IEnumerable<T> where T : IComparable <T>
    {
        private List<T> mHeap;
		.....


    }

It's not very clear, in short, to make the data structure support foreach operations.

2. How to understand IEnumerable and IEnumerator in C
In C, IEnumerator is equivalent to iterator iterator in C++ through IEnumerable interface, which enables the use of foreach operation for specific data structures.

Assuming that we don't have an IEnumerable interface to implement foreach operations using IE numerator iterators, we will do this:

//Suppose the iterator is itor and the class is Example
Example example;
IEnumerator itor = example.GetEnumerator();
while(itor.MoveNext()) //If the next object is not empty
{
	Example exampleI = (Example)itor.Cureent ; Get the current object and pass it to exampleI
    //Dosomething....
} 

But C# sets up the IEnumerable interface for us, so that we can inherit a class from this interface, so that we can directly perform foreach operations on it.
For example, the container List in C #:

You can see that List supports various types of traversal foreach operations
At the same time, the array type of C # can be used foreach by default.

// Iterate over an array of items.
int[] myArrayOfInts = {10, 20, 30, 40};
foreach(int i in myArrayOfInts)
{
   Console.WriteLine(i);
}

What happens if you define a container without using the IEnumerable interface and use foreach directly?

//Define a vehicle type
 public class Car
    {
        public string name;
        public int price;
        public Car(string _name, int _price)
        {
            name = _name;
            price = _price;
        }
    }
    //Define a garage to store cars
    public class Garage
    {
        private Car[] carArray = new Car[4];
        // Fill with some Car objects upon startup.
        public Garage()
        {
            carArray[0] = new Car("Rusty", 30);
            carArray[1] = new Car("Clunker", 55);
            carArray[2] = new Car("Zippy", 30);
            carArray[3] = new Car("Fred", 30);
        }
    }
 public static void Main()
        {
            Garage garage = new Garage();
            foreach (Car c in garage)
            {
                Console.WriteLine(c.price);
            }
        }

Found wrong report, can not use foreach

The hint is that you need to add the public instance definition of GetEnumerator, that is, the function has no interface to use its iterator.

So you need to add traversable interface functions to the class:

 public IEnumerator GetEnumerator()
 {
     return carArray.GetEnumerator();
 }

At the same time, the class should be changed to:

public class Garage : IEnumerable

Finally, you can output:

Keywords: IE

Added by tomato on Fri, 04 Oct 2019 04:42:50 +0300