• C# Iterations: IEnumerator, IEnumerable and Yield


    Directly using IEnumerator for iterations

    Enumerators are used to read data in the collection. The foreach statement hides the complexity of the enumerators, but you can directly manipulate IEnumerator for customized iterations. Let's do an example:

    Code:

    List<string> myList = new List<string>();
    for (int i = 0; i < 10; i++)
    {
        myList.Add("Item " + i.ToString());
    }

    IEnumerator<string> myEnum = myList.GetEnumerator();
     
    myEnum.Reset();            
    myEnum.MoveNext();
    myEnum.MoveNext();
    myEnum.MoveNext();
    System.Console.WriteLine(myEnum.Current);
    myEnum.MoveNext();
    myEnum.MoveNext();
    System.Console.WriteLine(myEnum.Current);

    myEnum.Reset();

    myEnum.MoveNext();

    System.Console.WriteLine(myEnum.Current);

    Output:

    Item 2
    Item 4
    Item 0 

    In order to reach the first element, you should run MoveNext method of Enumerator. Initial Position of Enumerator does not point the first element.

    Implementing IEnumerable and IEnumerator on your custom objects

    An Enumerator shows you the items in a list or collection. Each instance of an Enumerator is a a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current) or move to the next one (IEnumerator.MoveNext). When you write aforeach loop in C#, the compiler generates code that uses an Enumerator.

     

    An Enumerable is a class that can give you Enumerators. It has a method called GetEnumeratorwhich gives you an Enumerator that looks at its items. When you write a foreach loop in C#, the code that it generates calls GetEnumerator to create the Enumerator used by the loop.

    IEnumerable interface should be implemented in order to use your custom objects in the form of a collection (series of values or objects). Which means you can use it directly with the foreach statement. IEnumerable interface has a method called GetEnumerator() which returns an object implemented IEnumerator. Let's do an example: PowersOfTwo class implements IEnumerable so any instance of this class can be accessed as a collection. 


    class PowersOfTwo : IEnumerable<int> 
    {       
        public IEnumerator<int> GetEnumerator()
        {
            return new PowersOfTwoEnumerator();
        }        
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }        
    }

    Test:

    PowersOfTwo p2 = new PowersOfTwo();
    foreach (int p in p2)
    {
        System.Console.WriteLine(p);
    }

    Output:

    2 4 8 16 32 64 128 256 512 1024


    Actually the magic trick lies in the PowersOfTwoEnumerator Class

        class PowersOfTwoEnumerator : IEnumerator<int>
        {
            private int index = 0;

            public int Current
            {
                get { return (int)System.Math.Pow(2, index); }
            }
     
            object System.Collections.IEnumerator.Current
            {
                get { return Current; }
            }

            public bool MoveNext()
            {
                index++;

                if (index > 10)
                    return false;
                else
                    return true;
            }

            public void Reset()
            {
                index = 0;
            }

            public void Dispose()
            {
            }
        }

    Current returns the same element until MoveNext is called. Initial index is zero each MoveNext method incriments the index by 1 up to 10 then it returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, Current is undefined. You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead. IEnumerator inherits IDisposible for performance only.

    Using The Yield Keyword

    yield keyword is introduced by C# 2.0 in order to implement iteartion easier. On the other hand it has some disadventages. Let's first look at the yield keyword.

    public IEnumerable<int> GetPowersofTwo()
    {
       for (int i = 1; i < 10; i++)
           yield return (int)System.Math.Pow(2, i);
       yield break;
    }

    Yield is not a feature of the .Net runtime. It is just a C# language feature. During compilation Compiler converts yield method and its class to instances of IEnumerable and IEnumerator implemented classes. 

    Criticism of the keyword "yield"

    "yield" has a couple of drawbacks first of all it is designed to simplify implementing iterations. But it can be used to write very ill designed code (like goto). There are many bad examples therefore I am not going to write one here. But using it for other than the intended purpose will make your code hard to follow.

    Second problem is that "yield" does not make sense in Object Oriented paradigm just like delegates. I believe as long as languages stick to a single paradigm they become more understandable and structured. When Microsoft introduced C# they decided to use delegates as an event mechanism, instead of interfaces. Delegates are function pointers and have no meaning in OOP. A similar problem exists for yield too, when you look at the above example, the method signature tells you that GetPowersofTwo will return an object implemented IEnumerable. But it is not the case.

  • 相关阅读:
    Python paramiko安装报错
    Python 函数返回值类型
    python 数据类型
    python — 模块(二)
    python — 模块(一)
    python 总结
    python 小知识3
    python 小知识3
    python 小知识2
    python — 计算机基础知识
  • 原文地址:https://www.cnblogs.com/qiengo/p/2863937.html
Copyright © 2020-2023  润新知